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
}
}
Could you please find the error:
I got the wrong answer as: 140625001
but the correct output is: 336781474
Likely a precision error, try to use
longrather thanintand if that still does not give you the right answer useBigIntegerwhich is an arbitrary precision number.