-
Leetcode 50. Pow(x, n)개발/Leetcode 2023. 7. 24. 12:36
https://leetcode.com/problems/powx-n/description/
Pow(x, n) - LeetCode
Can you solve this real interview question? Pow(x, n) - Implement pow(x, n) [http://www.cplusplus.com/reference/valarray/pow/], which calculates x raised to the power n (i.e., xn). Example 1: Input: x = 2.00000, n = 10 Output: 1024.00000 Example 2: Inpu
leetcode.com
문제
pow(x,n) x의 n승을 계산하는 함수를 구현하여라
코드
class Solution:def myPow(self, x: float, n: int) -> float:ans = self.h(x, abs(n))return float(ans) if n >= 0 else 1 / ans
def h(self, base, n):if n == 0:return 1
if n % 2 == 0:return self.h(base * base, n / 2)else:return base * self.h(base * base, (n-1) / 2)public class Solution{public double MyPow(double x, int n){long N = Math.Abs(n);bool isNeedReverse = n < 0;
return isNeedReverse ? 1 / rec(x, N) : rec(x, N);}
public double rec(double b, long n){if (n == 0){return 1;}double bb = rec(b, n / 1);return n % 2 == 0 ? bb * bb : b * bb * bb;}}
'개발 > Leetcode' 카테고리의 다른 글
Leetcode 1870. Minimum Speed to Arrive on Time (0) 2023.07.26 Leetcode 852. Peak Index in a Mountain Array (0) 2023.07.25 Leetcode 735. Asteroid Collision (0) 2023.07.20 Leetcode 435. Non-overlapping Intervals (0) 2023.07.19 Leetcode 146. LRU Cache (0) 2023.07.18