LeetCode 7
-
bit manipulation 总结
326. The power of three
第一个方法,是用n%3 检查n是否能被3整除,如果不行则可以直接退出。如果可以,拿n/3,直到n == 1 的时候,证明n一定是3^n。
第二个方法,base:10的时候,10的power: 10, 100, 1000 全都是以1开头0结尾
base:2的时候,2的power:10, 100,1000全都是以1开头0结尾
可以用String baseChange = Integer.toString(number, base):
boolean powerOfThree = baseChange.match("^10*$"): 检查是否符合正则表达式
- Assumption:TC:O(log3n)
Integer.toString()
- Base conversion is generally implemented as a repeated division. The complexity of should be similar to our approach #1: O(log3n)String.matches()
- Method iterates over the entire string. The number of digits in the base 3 representation ofn
is O(log3n).
第三个方法,
The way to compute the maxInt: Integer.MAX_VALUE or 2^31 - 1;
最大能被3整除的数字是:
public class Solution { public boolean isPowerOfThree(int n) { return n > 0 && 1162261467 % n == 0; } }