Advertisement
vaibhav1906

Pow(x,n)

Dec 18th, 2021
1,627
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.62 KB | None | 0 0
  1. class Solution {
  2. public:
  3.    
  4.     double helper(double x, long long int n){
  5.        
  6.         if(n==0)return 1;
  7.        
  8.         if(n%2==0){
  9.             double k = helper(x,n/2);
  10.             return k*k;
  11.         }
  12.        
  13.         return x*helper(x,n-1);
  14.        
  15.     }
  16.    
  17.     double myPow(double x, long long int n) {
  18.        
  19.         int flag = 0;
  20.        
  21.         if(n<0){
  22.             flag = 1;
  23.             n = -1*n; //n = abs(n);
  24.         }
  25.      
  26.         double ans = helper(x,n);
  27.        
  28.         if(flag==1){
  29.             return 1/ans;
  30.         }
  31.        
  32.         return ans;
  33.        
  34.     }
  35. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement