[leetcode] 342. Power of Four

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode] 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?

 

Solution:

 1 bool isPowerOfFour(int num) 
 2     {
 3         while (num >= 4)
 4         {
 5             if ((num & 0x03) != 0)
 6                 return false;
 7             num >>= 2;
 8         }
 9         
10         return num == 1;
11     }

 

a) num & (num - 1)可以用来判断一个数是否为2的次方数

b) 通过与0x55555555与运算

1 bool isPowerOfFour(int num) 
2 {
3         return num > 0 && !(num & (num - 1)) && (num & 0x55555555) == num;
4 }

 

以上是关于[leetcode] 342. Power of Four的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode191 Number of 1 Bits. LeetCode231 Power of Two. LeetCode342 Power of Four

[leetcode] 342. Power of Four

342. Power of Four(LeetCode)

LeetCode 342. Power of Four

leetcode 342. Power of Four

[leetcode-342-Power of Four]