๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm/LeetCode

๐Ÿ’ฏ Daily LeetCode Challenge Day_16 - Pow(x, n)

by HaningYa 2020. 7. 18.
728x90

 

Explore - LeetCode

LeetCode Explore is the best place for everyone to start practicing and learning on LeetCode. No matter if you are a beginner or a master, there are always new topics waiting for you to explore.

leetcode.com


๋ฌธ์ œ

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

Example 1:
Input: 2.00000, 10
Output: 1024.00000

Example 2:
Input: 2.10000, 3
Output: 9.26100

Example 3:
Input: 2.00000, -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25

Note:

  • -100.0 < x < 100.0
  • n is a 32-bit signed integer, within the range [โˆ’231, 231 โˆ’ 1]

์ฒ˜์Œ ์ฝ”๋“œ

class Solution {
    func myPow(_ x: Double, _ n: Int) -> Double {
        var answer = x
        if n > 0 {
            for i in 1..<n{
                answer = answer * x
            }
        }else{
            for i in n..<1 {
                answer = answer * 1/x
            }
        }
        return answer
    }
}

Test case 0.00001 2147483647 ์—์„œ Time Limit Exceeded

for ๋ฌธ์„ ์—†์• ์•ผ ํ•œ๋‹ค.

Recursion ์ด์šฉ

class Solution {
    func myPow(_ x: Double, _ n: Int) -> Double {
        print(x)
        if n < 0 {
            return 1/x * myPow(1/x, -(n+1))
        }
        if n == 0 { return 1}
        if n == 2 {
            return x*x
        }
        if n%2 == 0 { return myPow(x*x, n/2)}
        else { return x*myPow(x*x,n/2)}
    }
}

 

๊ทธ๋ƒฅ for ๋ฌธ์„ ๋Œ๋ฉด 2.0000, 100 input ์—์„œ 100๋ฒˆ์„ ๊ณ„์‚ฐํ•  ๊ฒƒ์ด๋‹ค.

๊ทธ๋Ÿฌ๋‚˜ ์œ„ ์ฝ”๋“œ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด 8 ๋ฒˆ๋งŒ์— ๊ณ„์‚ฐ์„ ์™„๋ฃŒํ•  ์ˆ˜ ์žˆ๋‹ค.

  1. 2.0
  2. 4.0
  3. 16.0
  4. 256.0
  5. 65536.0
  6. 4294967296.0
  7. 1.8446744073709552e+19
  8. 3.402823669209385e+38

 

 

728x90

๋Œ“๊ธ€