Leetcode.com problem 50: "Pow(x,n)"

James S. Plank

Tue Aug 23 23:36:34 EDT 2022


In case Leetcode's servers are down

Implement the following method in the following class definition:

class Solution {
  public:
    double myPow(double x, int n);
};

Constraints:


The examples

UNIX> echo 2 10 | a.out
1024
UNIX> echo 2.1 3 | a.out
9.261
UNIX> echo 2 -2 | a.out
0.25
UNIX> 

Hints

Let's suppose that n equals 11 and look at n in binary: 1011. You can confirm that:

x11 = x8 * x2 * x1

or

x11 = x23 * x21 * x20

Does that give you enough information to solve the problem? Let's do another example -- suppose that x is 1.000001 and n is 2326. In hex, n is 0x916, so in binary, n is 1001 0001 0110.

Now, let's take a look at x2i for 1 from 0 to 11:

x20: 1.000001
x21: 1.000002
x22: 1.000004
x23: 1.000008
x24: 1.000016
x25: 1.000032
x26: 1.000064
x27: 1.000128
x28: 1.000256
x29: 1.000512
x210: 1.001025
x211: 1.002050

You'll note that you can calculate each of these values from the previous value with one multiplication. So, using the binary format of n:

x0x916 = x211 * x28 * x24 * x22 * x21

or

1.002050 * 1.000256 * 1.000016 * 1.000004 * 1.000002 = 1.002329

UNIX> echo 1.000001 2326 | a.out
1.00233
UNIX> 
You'll need to treat negative exponents differently, and since n can be -231 but 231 does not fit into an int, you'll do best to use long long's instead of ints. I'm pretty sure that this is the reason why the acceptance rate is so low.