C++ Solution by Counting trailing zeros


  • 0
    G
     class Solution {
         public:
        	 bool isPowerOfFour(int num) {
        	     if(num<=0)
        	        return false;
        	     int zeros = int(log(num&(-num))/log(2)); //get trailing zeros
        		 return ((num&(num-1))==0)&&(zeros%2==0)?true:false;
        	 }
         };
    

    the basic idea is that :

    • if one number is power of four,it should also be the power of two,so we have num&(num-1)==0
    • besides ,by observing numbers of 4's power:0,4,16...We find that all these numbers'
      trailing zeros are multiples of 2,so counting the trailing zeros of a number in binary form should be helpful

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.