您的位置:首页 > 其它

《leetCode》:Power of Three

2016-03-20 15:57 477 查看

题目

Given an integer, write a function to determine if it is a power of three.

Follow up:
Could you do it without using any loop / recursion?


思路一:不能AC

开始由于没有想到好的思路,因此,想着要不利用循环来做下,即利用循环把3的所有次方均从小到大求一次并与n进行比对。

以下代码思路报 内存错误。

public boolean isPowerOfThree(int n) {
if(n<=0){
return false;
}
List<Integer> list=new ArrayList<Integer>();
list.add(1);
while(true){
int temp=list.get(list.size()-1)*3;
if(temp>Integer.MAX_VALUE){
break;
}
list.add(temp);
}
if(list.contains(n)){
return true;
}
return false;
}


想着不用存储也行呀,然后就有了如下的代码;当n=2147483647报超时错误。

public boolean isPowerOfThree(int n) {
if(n<=0){
return false;
}
if(n==1){
return true;
}
int res=1;
while(true){
res=res*3;
if(res>Integer.MAX_VALUE||res>n){
break;
}
if(res==n){
return true;
}
}
return false;
}


呜呜,因此,也就只能想其它办法了。

思路二

在讨论组,看了下别人的代码,发现了如下思路;

找出在int范范围内最大的3次方的值maxValue,然后判断maxValue与n的余数是否为零,如果为零,则说明为3的次方。

public boolean isPowerOfThree(int n) {
if(n<=0){
return false;
}
int max3PowerValue= 1162261467; // 3^19,
int maxInt= 1162261467; // 2^31-1;
return max3PowerValue%n==0;
}


此思路虽然AC了,但是,和上面两种没有AC的方法区别不大。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: