Leetcode Power of Two
Given an integer, write a function to determine if it is a power of two.
Java code:(两种方法,第二种方法很妙,用到了bit wise )
第二种方法解题思路:
如果一个整数是2的幂,那么它的二进制形式最高位为1,其余各位为0
等价于:n & (n - 1) = 0,且n > 0
1 /* 2 * 1 = 2^0, true 3 * */ 4 public class PowerOfTwo { 5 public static void main(String[] args) { 6 int x =1023; 7 boolean y = isPowerOfTwo(x); 8 System.out.println(y); 9 } 10 11 /* 12 * method1 13 */ 14 public static boolean isPowerOfTwo(int n) { 15 if(n <= 0 ) {return false;} 16 while(n %2 == 0 ) { 17 n = n/2; 18 } 19 if(n==1) {return true;} 20 return false; 21 } 22 23 /* 24 * method2 25 * */ 26 public static boolean isPowerOfTwo(int n) { 27 int x = n & (n-1); 28 return (n > 0) & (x==0); 29 } 30 }
Reference:
1. http://bookshadow.com/weblog/2015/07/06/leetcode-power-of-two/