記錄

[JS] 50. Pow(x, n) 본문

FRONTEND STUDY/LeetCode

[JS] 50. Pow(x, n)

prts 2022. 10. 8. 00:12

문제 링크: https://leetcode.com/problems/powx-n/
난이도: Medium

 

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

 

pow(x, n)를 구현합니다. pow(x, n)는 power n(즉,  xⁿ)으로 상승된 x를 계산합니다.

 

 

Example 1:

Input: x = 2.00000, n = 10
Output: 1024.00000

Example 2:

Input: x = 2.10000, n = 3
Output: 9.26100

Example 3:

Input: x = 2.00000, n = -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25

 

Constraints 제한 조건:

  • -100.0 < x < 100.0
  • -2³¹ <= n <= 2³¹-1
  • n is an integer.  n은 정수입니다.
  • -104 <= xⁿ <= 104

 

문제 풀이

 

1.

기본 연산자와 메서드 활용

 

- 연산자를 이용해 x와 n을 거듭제곱

- Math.pow()로 xⁿ을 구하고 toFixed로 자바스크립트 소수 오류를 수정 > toFixed를 사용하면 타입이 string이 되기 때문에 parseFloat로 실수 변환

//단순 연산자
var myPow = function(x, n) {
	return x**n;
};

//메서드 활용
var myPow = function(x, n) {
	return parseFloat(Math.pow(x,n).toFixed(6))
};

 

2.

재귀 활용 풀이

var myPow = function(x, n) {
    if (n===0) return 1;
    if (n<0) return myPow(1/x,-n);
    //n<0, 1/x**-n
    
    return n % 2 === 0 ? myPow(x*x, n/2) : x* myPow(x*x, (n-1)/2); 

    //삼항 연산자 if 문으로 풀어 써 보기
    // if(n % 2 === 0){
    //     return myPow(x*x, n/2); //n이 짝수일 때
    // }else {
    //     return x* myPow(x*x, (n-1)/2);  //n이 홀수일 때
    // }
};

 

//n이 짝수일 때
x ^ n = (x * x) ^ (n / 2)

//n이 홀수일 때
x ^ n = ((x * x) ^ ((n - 1) / 2)) * x

 

'FRONTEND STUDY > LeetCode' 카테고리의 다른 글

[JS] 34. Find First and Last Position of Element in Sorted Array  (1) 2022.10.14
[JS] 136. Single Number  (0) 2022.10.12
[JS] 215. Kth Largest Element in an Array  (0) 2022.10.11
[JS] 7. Reverse Integer  (0) 2022.10.08
[JS] 01. Two Sum  (0) 2022.10.07
Comments