Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Method 1:
- Algorithm: SHIFT and count the number of 1
- Integer的范围是(-2^31) ~ (2^31-1), 32位是符号位
- */
- public boolean isPowerOfTwo(int a) {
- int count = 0;
- for(int i=0;i<31;i++) {
- if(((a>>i) & 1) == 1) {
- count++;
- }
- }
- return count <=1;
- }
- /*
- Method 2:
- 3 = 11
- 4 = 100
- 7 = 111
- 8 = 1000
- 所有的power of 2 number都有一个特性 number & (number -1) = 0
- */
- public boolean isPowerOfTwo(int a) {
- if(a < 1) {
- return false;
- }
- return (a & (a-1)) == 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement