LeetCode: 50. Pow(x, n)

1. 原题链接

https://leetcode.com/problems/powx-n/description/

2. 题目要求

给出一个double类型的 x 作为底数,int类型的 n 作为指数,求幂

3. 解题思路

这题看上去很简单,用一个for循环将底数 x 连乘 n次即可。但是要注意以下陷阱:

(1)n为负数时,求的是 1/x 连乘 -n 次;

(2)当 n 为Integer.MIN_VALUE时,直接返回0

4. 代码实现

public class Pow50 {
    public static void main(String[] args) {
        double x = 2;
        int n = 10;
        System.out.println(myPow(x, n));
    }
    public static double myPow(double x, int n) {
        if (n == 0) return 1;
        if (x == 1) return 1;
        if (x == -1) {
            if (n % 2 == 0) return 1;
            else return -1;
        }
        if (n == Integer.MIN_VALUE ) return 0;
        if (n < 0) {
            n = -n;
            x = 1 / x;
        }
        double res = 1.0;
        while (n > 0) {
            if ((n & 1) != 0)
                res *= x;

            x = x * x;
            System.out.println("x "+x);
            System.out.println("res "+res);
            n = n >> 1;
            System.out.println("n "+n);
        }
        return res;
    }
}

  

posted @ 2018-01-18 16:38  一只敲码的猫  阅读(156)  评论(0编辑  收藏  举报