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?

 

判断一个数是不是4的次方

 

C++(6ms):

1 class Solution {
2 public:
3     bool isPowerOfFour(int num) {
4         return (num&(num-1))==0 && (num-1)%3==0 ;
5     }
6 };

 

 

C++(9ms):

 1 class Solution {
 2 public:
 3     bool isPowerOfFour(int num) {
 4         if (num&(num-1))
 5             return false ;
 6         if (num < 0)
 7             return false ;    
 8         while(num){
 9             if (num&1)
10                 return true ;
11             num>>=2 ;
12         }
13         return false ;
14     }
15 };

 

 

java(3ms):

1 class Solution {
2     public boolean isPowerOfFour(int num) {
3         return (num&(num-1))==0 && (num-1)%3==0 ;
4     }
5 }

 

posted @ 2017-11-10 14:57  __Meng  阅读(134)  评论(0编辑  收藏  举报