342. Power of Four

第一种是普通的方法,但是注意不能溢出,因为不断乘以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     }

 

posted @ 2016-07-21 06:37  warmland  阅读(139)  评论(0编辑  收藏  举报