LeetCode-Pow(x, n)
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; }
posted on 2015-04-12 07:40 amethystltt 阅读(138) 评论(0) 编辑 收藏 举报