50. Pow(x, n)

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);
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 题目描述 Implement pow(x, n).实现x的n次方计算 问题分析 暴力求解 考虑极端输入:2.1 结...
    一里山阅读 336评论 0 0
  • Medium这道题要先处理n为奇偶和n为正负,难在处理edge case.比如当n = Integer.MIN_V...
    greatseniorsde阅读 190评论 0 0
  • Implement pow(x, n). Hide Company TagsLinkedIn Google Blo...
    番茄晓蛋阅读 210评论 2 1
  • Mediumn为负数的时候,取n= -(n + 1)因为怕遇到Integer.MIN_VALUE取负出现溢出
    greatseniorsde阅读 123评论 0 0
  • LeetCode 50 Pow(x, n) Implement pow(x, n). 遇到math类的题,比如po...
    ShuiLocked阅读 2,031评论 1 2