码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode] 342. Power of Four

时间:2016-06-10 17:51:47      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://www.cnblogs.com/ym65536/p/5573882.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!