PisecesPeng / PisecesPeng.record.me

:beach_umbrella: All things are difficult before they are easy
MIT License
3 stars 1 forks source link

3的幂 #18

Closed PisecesPeng closed 3 years ago

PisecesPeng commented 3 years ago

3的幂

给定一个整数, 写一个函数来判断它是否是'3'的幂次方.
如果是, 返回true; 否则, 返回false.

整数'n'是'3'的幂次方需满足: 存在整数'x'使得n == 3x

示例 1: 
输入: n = 27
输出: true

示例 2: 
输入: n = 0
输出: false

示例 3: 
输入: n = 9
输出: true

示例 4: 
输入: n = 45
输出: false

提示:

进阶:


题目地址: https://leetcode-cn.com/problems/power-of-three/

PisecesPeng commented 3 years ago

解题思路

代码

private static boolean func(int n) {
    if (n <= 0) return false;
    long three = 81l;
    while (three < n)  // 尽快超过入参
        three *= 81l;
    while (three > n)
        three /= 3l;
    if (three == n) return true;
    else return false;
}
PisecesPeng commented 3 years ago

LeetCode题解

解题思路

代码

private static boolean func(int n) {
    return Integer.toString(n, 3).matches("^10*$");
}
PisecesPeng commented 3 years ago

LeetCode题解

解题思路

代码

public static boolean func(int n) {
    return n > 0 && 1162261467 % n == 0;
}