[Leetcode] Power of Three

Given an integer, write a function to determine if it is a power of three.

判断一个数是否为3的幂:

一,除数法,最容易想到的方法:

1. 首先是能够整除

2. 整除到最后的数一定为1则说明TRUE否则FALSE

bool isPowerOfThree(int n) {
    if (n <= 0)
        return false;
    
    while(0 == (n % 3)){
        n/=3;
    }    
    
    return (n == 1);
}
二,根据整型数的特点,总结规律

boolean isPowerOfThree(int n) {
        return (n > 0) && (1162261467 % n == 0);
}

引用从解答中的分析:

  • MaxInt = \frac{ 2^{32} }{2} - 122321 since we use 32 bits to represent the number, half of the range is used for negative numbers and 0 is part of the positive numbers

Knowing the limitation of n, we can now deduce that the maximum value of n that is also a power of three is 1162261467. We calculate this as:

3^{\lfloor{}log_3{MaxInt}\rfloor{}} = 3^{\lfloor{}19.56\rfloor{}} = 3^{19} = 11622614673log3MaxInt=319.56=319=1162261467

Therefore, the possible values of n where we should return true are 3^0303^131 ... 3^{19}319. Since 3 is a prime number, the only divisors of 3^{19}319 are 3^0303^131 ... 3^{19}319, therefore all we need to do is divide 3^{19}319 by n. A remainder of 0 means n is a divisor of 3^{19}319 and therefore a power of three.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值