Given an Integer (signed), write a function to check whether it is a power of 4.
Example: Given num = +, return true. Given num = 5, return false.
followup: Could solve it without loops/recursion?
Main topic:
Given an integer (32-bit signed), the Write function determines whether it is a power of 4.
Test with For example a topic description.
think further: can you solve the problem without looping/recursion?
Problem Solving Ideas:
If an integer is a power of 4, then the second binary form (only one 1, 0 on odd digits) has the following characteristics:
1. The highest bit is 1 and the remaining bits are 0
2.0 is an even number
Condition 1 can be judged with num & (num-1) = = 0
Condition 2 can be judged with num & 0x55555555 > 0, (0x55555555) <==> 1010101010101010101010101010101, if the obtained number is itself, You can be sure that it is 4 of the number of times:
1 classSolution {2 Public:3 BOOLIspoweroffour (intnum) {4 if(num<=0)return false;5 Else return((num& (num-1))==0) && (num&0x55555555)==num);6 }7};
Using the Loop method:
1 classSolution {2 Public:3 BOOLIspoweroffour (intnum) {
if (num < 0) return false;4 intNumofone =0;5 while(num > 0) {6 if(Num &1)7numofone++;8 if(Num >>1) &1)9 return false;TenNum >>=2; One } A if(Numofone = =1) - return true; - Else the return false; - } -};
Leetcode 342. Power of Four