
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 ๋ฒ๋ง์ ๊ณ์ฐ์ ์๋ฃํ ์ ์๋ค.
- 2.0
- 4.0
- 16.0
- 256.0
- 65536.0
- 4294967296.0
- 1.8446744073709552e+19
- 3.402823669209385e+38
'Algorithm > LeetCode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๐ฏ Daily LeetCode Challenge Day_18 - Course Schedule 2 (0) | 2020.07.24 |
---|---|
๐ฏ Daily LeetCode Challenge Day_17 - Top K Frequent Elements (0) | 2020.07.18 |
๐ฏ Daily LeetCode Challenge Day_15 - Reverse Words in a String (0) | 2020.07.16 |
๐ฏ Daily LeetCode Challenge Day_14 - Angle between hands of a clock (0) | 2020.07.14 |
LeetCode - Container With Most Water (0) | 2020.07.14 |
๋๊ธ