Pow(x,n) Problem


Description

LeetCode Problem 50.

Implement pow(x, n), which calculates x raised to the power n (i.e., x^n).

Example 1:

1
2
Input: x = 2.00000, n = 10
Output: 1024.00000

Example 2:

1
2
Input: x = 2.10000, n = 3
Output: 9.26100

Example 3:

1
2
3
Input: x = 2.00000, n = -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25

Constraints:

  • -100.0 < x < 100.0
  • -2^31 <= n <= 2^31-1
  • -10^4 <= x^n <= 10^4


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
    double myPow(double x, int n) {
        if (n == 0)
            return 1;
        
        bool neg = (n < 0) ? true : false;
        long long m = abs(n);
        double ans = 1;
        
        while (m > 0) {
            if (m & 1) 
                ans *= x;
            x *= x;
            m = m >> 1;
        }
        
        if (neg)
            return 1 / ans;
        else
            return ans;
    }
};




Related Posts

Permutation Sequence Problem

LeetCode 60. Given n and k, return the kth permutation...

Regular Expression Matching Problem

LeetCode 10. Given an input string s and a pattern...

Pow(x,n) Problem

LeetCode 50. Determine if a 9 x 9 Sudoku board...