Title Link: https://leetcode.com/problems/power-of-four/
Topic:
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?
Ideas:
Observing 4 powers, it was found that except the highest bit, it was 0, and the number of 0 was even, such as 4=100 16=10000, 8=1000. Otherwise, it's not 4 power.
Algorithm:
public static Boolean ispoweroffour (int num) { if (num==1) return true; if (num==2| | num==3) return false; if (num<1) return false; String binary = integer.tobinarystring (num); Char c[] = Binary.tochararray (); int count = 0; for (int i=1;i<c.length;i++) {//Except the beginning is all 0 if (c[i]!= ' 0 ') { return false; } else{//Statistics 0 of the number of count++; } } if (count!=0&&count%2==0)//has an even number of 0 return true; else return false; }
"Leetcode" Power of Four