326. Power of Three / 342. Power of Four

5 篇文章 0 订阅
3 篇文章 0 订阅

326. Power of Three:

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

Follow up:

Could you do it without using any loop / recursion?

代码:

class Solution {
public:
    bool isPowerOfThree(int n) {
        return n>0?!(1162261467 % n):0; //162261467 = 3^19
    }
};

3的幂的数也就下面这些:

1||3||9||27||81||243||729||2187|| 6561||  19683 || 59049 || 177147 || 531441 ||  1594323 || 4782969 || 14348907 || 43046721 || 129140163 || 387420489 ||  162261467

162261467(3^19,最大的那个)肯定能被  3^n 整除,n=1....19。

那么怎么证明162261467不能被 3^n - 3^(n+1) 之间的数整除呢?

例如n=5:

               3^19 / ( 3^5+0) --- 3^19 / ( 3^5+1)---3^19 / ( 3^5+3^5) ----3^19 / ( 3^5+2*3^5-1) ----3^19 / ( 3^5+2*3^5)

分别为:3^14/(1+0)--- 3^14 / ( 1+1/3^5)---3^14 / ( 1+1) ----3^14/ ( 1+2-1/3^5) ----3^14 / (3^5+2)

这些分母都在(1,3)之间(开区间)。所以不可能再整除3^14了。

所以说区间(3^5, 3^6)之间的数都不能整除3^19了。


342. Power of Four:

Given an integer (signed 32 bits), write a function to check whether it is a power of 4.

Example:
Given num = 16, return true. Given num = 5, return false.

Follow up: Could you solve it without loops/recursion?


4^15是最大值。与上面题目一样,eg: 4^15/(4^4)与 4^15/(4^5)之间还有个2*4^5能被4^15整除,反映在二进制数形式上面,就是只含有1个1的数都能被4^15整除,而真正满足条件的是,只有偶数位为1的数才是4的power。这时就要想办法排除这种情况。

可以用 (num&0x55555555)==num来排除2*(2^n)的情况,也就是排除奇数位为1的那些数。

代码:

class Solution {
public:
    bool isPowerOfFour(int num) {
        if(num<=0) return false;
        int max = pow(4,15);
        return (max%num==0&&(num&0x55555555)==num)?true:false;
    }
};


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值