LeetCode 342. Power of Four

https://leetcode.com/problems/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?

  • 数学题+位运算。
  • 因为是signed 32 bits,所以先保证num > 0。
  • 然后2的幂的特征(num & (num - 1)) == 0,e.g. 0x1000 & 0x0111。
  • 再对2的幂中筛选不是4的幂的。4的幂的二进制中1总是出现在奇数位,e.g. 4^1(0x0100), 4^2(0x00010000), 4^3(0x01000000),其他则是在偶数位,e.g. 2^1(0x0010), 2^3(0x1000), 2^5(0x00100000)。所以(num & 0x55555555) != 0,这里0x55555555正是signed 32 bits integer。
  • 之前没注意位运算运算符&优先级低于==,需要加上括号。
  • C语言运算符_百度百科
    • http://baike.baidu.com/link?url=7D3QzeLlfI9pELy4OqJyyGE-WwRZhZ_mCI8ZSI6YdQHrldIIly3WnCTGnjzbypatAAodGjGFTUrTGJxkIbWFBq#2
  • 还有一种解法(4^n - 1)都可以被3整除,所以可以判断(num > 0) && ((num & (num - 1)) == 0) && ((num - 1) % 3 == 0)
复制代码
 1 #include <iostream>
 2 using namespace std;
 3 
 4 class Solution {
 5 public:
 6     bool isPowerOfFour(int num) {
 7         return ((num > 0) && ((num & (num - 1)) == 0) && ((num & 0x55555555) != 0));
 8     }
 9 };
10 
11 int main ()
12 {
13     Solution testSolution;
14     bool result;
15     
16     result = testSolution.isPowerOfFour(16);    
17     cout << result << endl;
18         
19     char ch;
20     cin >> ch;
21     
22     return 0;
23 }
View Code
复制代码

 

posted on   浩然119  阅读(213)  评论(0编辑  收藏  举报
努力加载评论中...

点击右上角即可分享
微信分享提示