计算a^n % b,其中a,b和n都是32位的整数。
样例
例如 231 % 3 = 2
例如 1001000 % 1000 = 0
挑战
O(logn)
Calculate the a^n % b where a, b and n are all 32bit integers.
Example
For 231 % 3 = 2
For 1001000 % 1000 = 0
Challenge
O(logn)
不懂快速幂的小伙伴请看:http://blog.csdn.net/xuruoxin/article/details/8578992
思路:http://blog.csdn.net/y990041769/article/details/22311889
class Solution {
/*
* @param a, b, n: 32bit integers
* @return: An integer
*/
public static int fastPower(int a, int b, int n) {
if(b == 0 || n < 0) return 0;
if(b == 1 && n == 0) return 0;
long result = 1l, atem = a;
while(n > 0) {
if((n & 1) == 1) {//n的最后一位为1
result = (result * atem) % b;
}
atem = (atem % b) * (atem % b) % b;
n >>= 1;
}
return (int)result;
}
};