given an integer, write a function to determine if it is a power of two.git
Example 1:github
Input: 1 Output: true Explanation: 20 = 1
Example 2:測試
Input: 16 Output: true Explanation: 24 = 16
Example 3:code
Input: 218 Output: false
我想既然是2的乘方,那麼在Int範圍內也沒多少個呀,那麼列出來比較總能夠吧leetcode
這裏用了Long類型,那麼由於pow返回轉爲int的時候 31次方會變爲2147483647。it
public static List<Long> list = new ArrayList<>(); static { for(int i= 0;i<32;i++){ list.add((long) Math.pow(2D,i)); } } public static boolean isPowerOfTwo(int n) { if(list.contains(Long.valueOf(n))){ return true; } return false; }
好比這樣:io
System.out.println( (int)Math.pow(2D,31)); out:2147483647 System.out.println( (long) Math.pow(2D,31)); out:2147483648
看了一下其餘人的寫法function
//這是大神寫的 沒辦法 public static boolean isPowerOfTwo2(int n) { if(n<=0) { return false; } return (n&(n-1)) <= 0 ; }
既然這樣,就是判斷一個1吧List
//在二進制中 2的乘方只會存在一個1 public static boolean isPowerOfTwo3(int n) { return n>0 && Integer.bitCount(n) == 1; }
而後測試一下:二進制
System.out.println(isPowerOfTwo2(1)); System.out.println(isPowerOfTwo2(16)); System.out.println(isPowerOfTwo2(218)); System.out.println(isPowerOfTwo2(2147483647));
git:https://github.com/woshiyexinjie/leetcode-xin