美文网首页
50. Pow(x, n)

50. Pow(x, n)

作者: Super_Alan | 来源:发表于2018-04-22 02:31 被阅读0次

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

    一道无聊的二分。注意 n 为 Integer.MIN_VALUE的情况,-n 为 0.

    class Solution {
        public double myPow(double x, int n) {
            if (n == 0) {
                return 1;
            }
            
            if (n == Integer.MIN_VALUE) {
                return myPow(x, -1) * myPow(x, n + 1);
            }
            
            if (n < 0) {
                x = 1 / x;
                n = -n;
            }
            
            return (n % 2 == 0) ? myPow(x*x, n/2) : x * myPow(x*x, n/2);
        }
    }
    

    相关文章

      网友评论

          本文标题:50. Pow(x, n)

          本文链接:https://www.haomeiwen.com/subject/mgkqlftx.html