Java Pow Of 2 给了我一个错误的答案

问题描述 投票:0回答:1
class Solution {
    int mod = (int) (1e9) + 7;

    int modPow(long base, long exponent) {
        if (exponent == 0) return 1;

        long result = 1;
        while (exponent > 0) {
            if (exponent % 2 == 1) {
                result = (result * base) % mod;
            }
            base = (base * base) % mod;
            exponent /= 2;
        }
        return (int) result;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        int result = solution.modPow(2, (long) 1e9);
        System.out.println(result); // Output: 336781474
    }
}

请您找出错误所在:
我得到的错误答案是:140625001
但正确的输出是:336781474

java performance exponential pow
1个回答
0
投票

可能存在精度错误,请尝试使用

long
而不是
int
,如果仍然无法给出正确答案,请使用
BigInteger
,这是一个任意精度数字。

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