Problems encountered today is LeetCode 231 questions. The problem is a simple question, asked to enter a number n, determine the number is not a power of 2
to see this problem, the first thought is to use bit operation, because binary bit computing is more efficient
my own solution It is the following code:
public static boolean judge(int n){ int num=1; boolean flage=false; while (num<=n){ if (num==n){ flage=true; break; }else { num=num<<1; } } return flage; }
However, this scheme n particularly when time out. After the reference to other people's answers to the program, I found that if a number n is a power of 2, then the number must meet three conditions:
① the highest binary number is 1, the other bits are 0;
② the number minus one of the most significant bit is 0, the other bit is a 1;
③ The number must be greater than 0
and therefore can be utilized in the position calculation, as follows:
public static boolean judge2(int n){ //if (n<=0) return false; //return ((n&(n-1))==0); //或者写成 return n>0 && (n&(n-1))==0; }