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

Hiring now

Get the Goldman Sachs interview, not just the prep

landed applies to roles like these for you, on each company’s own site, with answers written for the role.

Get 5x interviews10 free auto-applies. No card.
Or practice this question first

Next question