Skip to content

Instantly share code, notes, and snippets.

@qingl97
Created July 6, 2016 11:45
Show Gist options
  • Save qingl97/9f1c815b00cecce730a3a3c953a242ce to your computer and use it in GitHub Desktop.
Save qingl97/9f1c815b00cecce730a3a3c953a242ce to your computer and use it in GitHub Desktop.
public class Solution {
public boolean isPowerOfTwo(int n) {
//return solutionOne(n);
//return solutionTwo(n);
return solutionThree(n);
}
private boolean solutionOne(int n) {
// check the result of divition by 2 iteratively
if(n == 0) return false;
while(n != 1) {
if(n%2 != 0) return false;
n = n/2;
}
return true;
}
private boolean solutionTwo(int n) {
if(n < 0) return false;
int count = 0;
while(n != 0) {
if((n & 1) == 1) ++count;
n = n>>1;
}
return count == 1 ? true : false;
}
private boolean solutionThree(int n) {
if(n<0) return false;
return Integer.bitCount(n) == 1 ? true:false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment