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

342. Power of Four

时间:2016-07-21 07:37:40      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:

第一种是普通的方法,但是注意不能溢出,因为不断乘以4之后,有可能超过Integer.MAX_VALUE

 1     public boolean isPowerOfFour(int num) {
 2         if(num == 1) {
 3             return true;
 4         }
 5         int power = 0;
 6         int curVal = 1;
 7         while(curVal < num && curVal < Integer.MAX_VALUE / 4) {
 8             curVal *= 4;
 9             power += 1;
10             if(curVal == num) {
11                 return true;
12             }
13         }
14         return false;
15     }

第二种是位操作。

1.如何判断是不是2的幂。

(num & (num - 1)) == 0

因为2的幂是10,100,1000,...也就是说,是一个以1开头,并且跟着一串0的数,如果减一取且,应该是0

2.如果是4的幂

除了满足2的幂之外,4的幂是这样的100,10000,1000000,也就是说一个1后面跟着偶数个0,所以要判断1是不是在偶数位上,让它与0101去且,如果不在偶数位上,就会得到0,在偶数位就不是0

 1     public boolean isPowerOfFour(int num) {
 2         if(num == 1) {
 3             return true;
 4         }
 5         int power = 0;
 6         int curVal = 1;
 7         while(curVal < num && curVal < Integer.MAX_VALUE / 4) {
 8             curVal *= 4;
 9             power += 1;
10             if(curVal == num) {
11                 return true;
12             }
13         }
14         return false;
15     }

 

342. Power of Four

标签:

原文地址:http://www.cnblogs.com/warmland/p/5690363.html

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