Pow(x,n)

Asked atGoldman SachsZoho
1Give yourself 5 minutes
2Answer out loud, not in your head
3Then compare with the answer below

The problem

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

**Note **: In output print 4 digits places after decimal point.

Input : x = 2.0000 , n = 10 Output : 1024.0000 Explanation : Answer = 2^10 => 1024.

Input : x = 2.0000 , n = -2 Output : 0.2500 Explanation : Answer = 2^(-2) = 1/4 => 0.25.

Input : x = 2.5000 , n = 2

  • -100.0 <= x <= 100.0
  • -231 <= n <= 231 - 1
  • -104 <= xn <= 104
  • Either x is not zero or n>0.
  • n is an integer.

cpp

class Solution {
public:
    double myPow(double x, int n) {
        //your code goes here
    }
};

java

class Solution {
    public double myPow(double x, int n) {
          //your code goes here
    }
}

python

class Solution:    
    def myPow(self, x, n):
        #your code goes here

javascript

class Solution {
    myPow(x, n) {
         //your code goes here
    }
}

csharp

public class Solution
{
    public double MyPow(double x, int n)
    {
        //your code goes here
    }
}

go

func myPow(x float64, n int) float64 {
    //your code goes here
}
Stuck? Show a way to structure it+
  1. 01Promote n to a wider signed type.
  2. 02Invert x and negate exponent when n is negative.
  3. 03Maintain result and current base.
  4. 04Square the base and halve the exponent.
  5. 05Multiply result whenever the current exponent bit is one.

Reference answer

Then expect these follow-ups

  • Can you write the recursive equivalent?

    Tests: follow-up reasoning

  • What numerical issues arise for very large magnitudes?

    Tests: constraint adaptation

Free to read · better with Enzo

Practice this out loud with Enzo

Enzo runs it as a mock interview, pushes back with follow-ups, and grades you on the rubric.

Next question