Advertisement here

Implement pow(x, n), which calculates x raised to the power n (i.e., xn) solution - Leetcode

 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution {
public:
    double myPow(double x, int n) {
        //if n is even x *=x and n /=2;
        // if n is odd n -=1; ans *=x
        
          long nn=1.0;
        
        if(n<0) nn=-1*(long)n;
        else nn=n;
        
        double ans=1.0;
        
        
        while(nn>0)
        {
            if(nn%2>0)
            {
               
                ans *=x;
                nn -=1;
            }
            else
            {
                 nn /=2;
                x *=x;
            }
        }
        if(n<0) return (double)(1.0)/ans;
        return ans;
    }
};
Next Post Previous Post
No Comment
Add Comment
comment url
Advertisement here