본문 바로가기

Algorithm/Leetcode

[Top Interview 150 - Math] 50. $Pow(x, n)$

[Q] [Medium]

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

 

  • pow(x, n) 을 구현하라고 해서 ** 로 return 했는데 통과
  • 뭔가 Medium 문제 인데 이렇게 풀어도 되나 다른 사람들 답도 찾아봤다.
# Answer

class Solution:
	def myPow(self, x: float, n: int) -> float:

	return x ** n

 

# 다른 사람 답

class Solution:
    def myPow(self, x: float, n: int) -> float:
        my_pow_num = pow(x, n)
        
        if my_pow_num > (pow(2, 31) - 1):
            my_pow_num = pow(2, 31) -1
        elif my_pow_num < (pow(2, 31)) * (-1):
            my_pow_num = pow(2, 31) * (-1)
            
        return my_pow_num