码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode-Pow(x, n)

时间:2015-04-12 08:03:11      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:

Q: Implement pow(x, n).

Note:

1. n = int.MinValue, Math.Abs(n) will overflow.

  For iterative, need to multiply x at the beginning, x value changes.

2. n = 3, make sure result is correct.

Recursive:

public double Pow(double x, int n) 
    {
        if(n == 0)
        {
            return 1;
        }
        
        int t = Math.Abs(n / 2);
        
        double result = Pow(x, t);
        
        if(n % 2 == 0)
        {
            result = result * result;
        }
        else
        {
            result = result * result * x;
        }
        
        return n > 0 ? result : 1/result;
    }

Iterative:

public double Pow(double x, int n) 
    {
            if (n == 0)
            {
                return 1;
            }

            double result = 1;

            int t = n != int.MinValue ? Math.Abs(n) : Math.Abs(n + 1);
            if (n == int.MinValue)
            {
                result *= x;
            }

            while (t > 0)
            {
                if (t % 2 == 0)
                {
                    x *= x;
                    t /= 2;
                }
                else
                {
                    result *= x;
                    t--;
                }
            }

            return n > 0 ? result : 1 / result;
    }

 

LeetCode-Pow(x, n)

标签:

原文地址:http://www.cnblogs.com/amethystltt/p/4419010.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!