• [x] ### 二分
  • [x] ### overflow
  • [x] ``` while (pow > 0) {

    if (pow % 2 != 0) {
        result *= x;
    }
     x *= x;
     pow /= 2;
    

    }

    ```

  • [ ] * [ ] 这个题目在leetcode上我以前写的过不了test case

min value - 2 ^ 31 ~ 2 ^31 - 1

当把负数转为正数次幂时候,会溢出

50.Pow(x, n)

Implementpow(x,n).

Example 1:

Input:
 2.00000, 10

Output:
 1024.00000

Example 2:

Input:
 2.10000, 3

Output:
 9.26100
time : Binary Search O(log(n))
space: O(1)

class Solution {
    public double myPow(double x, int n) {
        if (n == 0) {
            return 1;
        }
        if (n == 1) {
            return x;
        }
        long pow = Math.abs((long)n);
        double result   = 1;
        while (pow > 0) {
            if (pow % 2 != 0) {
                result *= x;
            }
            x *= x;
            pow /= 2;
        }
        if (n < 0) {
            return 1.0 / result;
        }
        return result;
    }
}
time : Binary Search O(log(n))
space: O(logn)
class Solution {
    public double myPow(double x, int n) {
        if (n > 0) {
            return pow(x, n);
        }else{
            return 1.0 / pow(x, -n);
        }
    }
    public double pow(double x, int n) {
        if (n == 0) {
            return 1;
        }
        double y = pow(x, n / 2);//////////////////////////////////////////////////
        if (n % 2 == 0) {
            return y * y;
        }else{
            return y * y * x;
        }
    }
}

第二种方法不用处理溢出

results matching ""

    No results matching ""