Leetcode 231 and 342. Power of 2, Power of 4

上原题先:

Leetcode 231 and 342. Power of 2, Power of 4

Leetcode 231 and 342. Power of 2, Power of 4

把Leetcode这两道题目放一起,其实这两个是相似的。

完全可以通过循环来做,在不能用循环的条件下如何求解?


方法一:通过考虑位运算。精妙绝伦的解法。

Leetcode 231 and 342. Power of 2, Power of 4


方法二:与方法一类似,只不过在满足num为2的幂前提下,决定num是不是4的幂的方法略微有差别:

Leetcode 231 and 342. Power of 2, Power of 4

理由如下:

Leetcode 231 and 342. Power of 2, Power of 4

至于为什么2^(2k)-1一定可以被3整除,可以通过数学归纳法证明。