Calculate the a^n % b where a, b and n are all 32bit integers.
For 2^31 % 3 = 2
For 100^1000 % 1000 = 0
这道题有个值得注意的问题,当n为奇数的时候,如果把递归写成:
long num = fastPower(a, b, n / 2);
return (int) ((a%b * num * num) % b);
这样的话在某些test case会溢出,所以最好还是写成以下的形式
class Solution { /* * @param a, b, n: 32bit integers * @return: An integer */ public int fastPower(int a, int b, int n) { // write your code here a %= b; if(n == 0) return 1 % b; if(n == 1) return a; if(n % 2 == 0){ long num = fastPower(a, b, n / 2); return (int) ((num * num) % b); } else{ long num = fastPower(a, b, n - 1); return (int) ((a * num) % b); } } };
时间: 2024-10-07 12:41:21