计算an % b,其中a,b和n都是32位的整数。
例如 231 % 3 = 2
例如 1001000 % 1000 = 0
这题要考虑输入的a,b是否为负数,结果是否溢出,是否超时,这里用到了分治递归class Solution {
public:
    /*
     * @param a, b, n: 32bit integers
     * @return: An integer
     */
    int fastPower(int a, int b, int n) {
        // write your code here
        long long res = 0;
        if (a == 0 || b==0)
            return 0;
         a = a%b;
        if (a>0) {
            res = power(a,b,n); 
           if (n <0) {
               res = 1/res;
           }
        }
        else {
            res = power(a,b,n);
            if (n%2 ==1) {
                res = 0-res;
            }
            if (n < 0) {
                res = 1/res;
            }
        }
        return res%b;
    }
    long long power(int a,int b,int n) {
            if (n == 0) {
                return 1;
            }
            if (n ==1) {
                return a;
            }
            long long result =  power(a,b,n>>1);
            result = result*result %b;
            if (n & 0x1 ==1) {
                result =result *a%b;
            }
            return result;
    }
};原文:http://blog.csdn.net/susser43/article/details/46663715