Advertisement
exmkg

Untitled

Aug 23rd, 2024
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.03 KB | None | 0 0
  1. class Solution {
  2.     public double myPow(double x, int n) {
  3.         long exponent = (long) n;
  4.  
  5.         // negative n, x^n = (1/x)^(-n)
  6.         // e.g. x^(-7) = (1/x)^7
  7.         if (exponent < 0) {
  8.             exponent = -exponent;
  9.             x = 1 / x;
  10.         }
  11.         return myPow_(x, exponent);
  12.     }
  13.  
  14.     // T: O(log n)
  15.     // S: O(log n)
  16.     private double myPow_(double x, long exponent) {
  17.         if (exponent == 0) return 1;
  18.  
  19.         // even n, x^n = (x^2)^(n/2)     = x^(2*(n/2))
  20.         // e.g. x^6 = (x^2)^3 = x^(2*3)
  21.  
  22.         // odd  n, x^n = (x^2)^(n/2) * x = x^(2*(n/2)) * x = x^(n-1) * x,
  23.         //                                                     because 2 * (n/2) = n - 1 for (n/2) is floored,
  24.         //                                                     i.e. for odd n = 7, n/2 will be 3, not 3.5
  25.         // e.g. x^7 = (x^2)^3 * x = x^(2*3) * x = x^6 * x
  26.         return (exponent % 2 == 0) ? myPow_(x * x, exponent / 2)
  27.                                    : myPow_(x * x, exponent / 2) * x;
  28.     }
  29. }
  30.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement