Created
July 6, 2016 11:45
-
-
Save qingl97/9f1c815b00cecce730a3a3c953a242ce to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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