《leetCode》:Power of Three

题目

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的方法区别不大。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值