java中的2的幂程序给出true,如果我传递数字为2147483647,为什么?

问题描述 投票:0回答:1

我尝试编写一个java程序来查找一个数字是2的幂,我在下面提到的那个数字。

我传递的数字为 2147483647,我的程序的输出返回 true 而不是 false。 谁能解释一下我在这里缺少什么概念以及如何纠正它。

节目

class Solution {
    public boolean isPowerOfTwo(int n) {
        int num = 0;
        int p = 0;
        while(num <= n){
            num = (int) Math.pow(2,p);
            p++;
            if(num == n){
            return true;
        }
        }
        
        return false;    

    }
}

    public static void main(String[] args) {
    
        enter code here
        boolean val = isPowerOfTwo(2147483647);
    
        }
java pow
1个回答
0
投票

如果

double
大于
Integer.MAX_VALUE
,则将其投射到
int
将得到
Integer.MAX_VALUE

您给出的数字是

Integer.MAX_VALUE
,所以当然它会是足够大的
(int) Math.pow(2, p)
值。

您将需要一种不同的方法,例如实际上将 int 值加倍,而不是仅仅调用

Math.pow
,或者一些更复杂的方法。 (通常的超优化解决方案是
x >= 0 && (x & (x - 1)) == 0
,但您可能还不明白它或为什么它有效。)

© www.soinside.com 2019 - 2024. All rights reserved.