본문 바로가기
LeetCode

[LeetCode] 50. Pow(x, n)

by JungSeung 2023. 11. 10.
728x90

https://leetcode.com/

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

 

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/2^2 = 1/4 = 0.25

 

Constraints:

  • -100.0 < x < 100.0
  • -2^31 <= n <= 2^31-1
  • n is an integer.
  • Either x is not zero or n > 0.
  • -10^4 <= xn <= 10^4

 

Code :

var myPow = function(x, n) {
    // 지수가 0일 때는 1을 반환
    if (n === 0) return 1;
    // 지수가 음수일 때는 x의 -(n)승의 역수를 반환
    if (n < 0) return 1 / myPow(x, -n);
    // 지수가 짝수일 때는 재귀적으로 x^(n/2)를 계산하여 제곱
    if (n % 2 === 0) {
        let half = myPow(x, n / 2);
        return half * half;
    } else {
        // 지수가 홀수일 때는 재귀적으로 x^(floor(n/2))를 계산하여 제곱한 후 x를 곱함
        let half = myPow(x, Math.floor(n / 2));
        return half * half * x;
    }
};

 

Solutions Code :

var myPow = function(x, n) {
    // 지수가 0인 경우 1을 반환
    if (n === 0) {
        return 1;
    }
    // 지수가 음수인 경우 x를 역수로 바꾸고 지수를 양수로 만듦
    if (n < 0) {
        x = 1 / x;
        n = -n;
    }
    // 지수가 짝수인 경우 재귀적으로 절반의 지수를 계산하여 제곱
    if (n % 2 === 0) {
        let halfPower = myPow(x, n / 2);
        return halfPower * halfPower;
    } else {
        // 지수가 홀수인 경우 x를 한 번 더 곱하고 나머지 부분은 재귀적으로 계산
        return x * myPow(x, n - 1);
    }  
};

 

 

출처 : https://leetcode.com/problemset/all/

 

Problems - LeetCode

Boost your coding interview skills and confidence by practicing real interview questions with LeetCode. Our platform offers a range of essential problems for practice, as well as the latest questions being asked by top-tier companies.

leetcode.com

 

728x90

'LeetCode' 카테고리의 다른 글

[LeetCode] 51. N-Queens  (0) 2023.12.21
[LeetCode] 5. Longest Palindromic Substring  (0) 2023.11.15
[LeetCode] 49. Group Anagrams  (0) 2023.11.10
[LeetCode] 48. Rotate Image  (2) 2023.11.10
[LeetCode] 47. Permutations II  (0) 2023.11.10