在Leetcode上看到一道题目:
Given an integer, write a function to determine if it is a power of three.
Example 1:
Input: 27
Output: true
Example 2:
Input: 0
Output: false
下面是Java代码:
class Solution {
public boolean isPowerOfThree(int n) {
if(n<1)
return false;
while(n % 3 == 0){
n/=3;
}
return n==1;
}
}
这个方法用了一个循环方法来解决,但是觉得这个方法有点不是那么简洁,就想到另外一种方法。
在以Decimal为基础时,10的倍数都会为1开头,后面紧跟着数字0,比如:10,100,1000.
以Binary 为基础时,102 , 1002, and 10002 这些都是分别对应210,410 and 810
根据这个思路,开头都是1,后面跟着都是数字0,这样组成的数字是以3为倍数来组成的。需要做的是将decimal的数字转换为以低为3的数字,然后需要去检查是否是以1开头,后面紧跟着0。
在Java中有一个函数很有用:
String baseChange = Integer.toString(number, base);
举个例子:
Integer.toString(5,2) == “101”
Integer.toString(5,3) == “12”
还有一个函数也是重要的:
boolean powerThree = baseChange.matches("^10*$");
用这个regular expression 来检查这个string是否以1开头和检查后面紧跟着一个0或者更多的0或者是后面什么都没有紧跟着。
下面就是代码实现了:
public class Solution{
public boolean isPowerOfThree(int n) {
String Change = Integer.toString(n, 3);
boolean Three = Change.matches("^10*$");
return Three;
}
}
如果有哪里写错,请指出来哦!