關鍵是弄明白2的冪的二進制形式只有一個1。spa
1 public class Solution { 2 public boolean isPowerOfTwo(int n) { 3 int count = 0; 4 if (n <= 0) { 5 return false; 6 } else { 7 while (n != 0) { 8 if ((n & 1) == 1) { 9 count++; 10 } 11 n = n >> 1; 12 if (count > 1) { 13 return false; 14 } 15 } 16 return true; 17 } 18 } 19 }
1 public class Solution { 2 public boolean isPowerOfThree(int n) { 3 if (n < 1) { 4 return false; 5 } 6 7 while (n % 3 == 0) { 8 n /= 3; 9 } 10 11 return n == 1; 12 } 13 }
10進制,1(100)、10(101)、100(102)……;code
2進制,1(20)、10(21)、100(22)……;blog
3進制,1(30)、10(31)、100(32)……;three
String baseChange = Integer.toString(number, base);
boolean matches = myString.matches("123");
1 public class Solution { 2 public boolean isPowerOfThree(int n) { 3 return Integer.toString(n, 3).matches("^10*$"); 4 } 5 }
3k = n,即 k = log3n 等價於 k = log10n / log103。若是n是3的冪,那麼k爲整數。leetcode
1 public class Solution { 2 public boolean isPowerOfThree(int n) { 3 return (Math.log10(n) / Math.log10(3)) % 1 == 0; 4 } 5 }