leetcode-50-pow()
2024-08-25 06:46:13
题目描述:
方法一:O(logn)递归:
class Solution:
def myPow(self, x: float, n: int) -> float:
if n == 0:
return 1
if n < 0:
return 1/self.myPow(x,-n)
if n&1:
return x*self.myPow(x,n-1)
return self.myPow(x*x,n//2)
迭代:
class Solution:
def myPow(self, x: float, n: int) -> float:
if n < 0:
x,n = 1/x,-n
ans = 1
while n > 0:
if n&1:
ans *= x
x *= x
n >>= 1
return ans
java版:
class Solution {
public double myPow(double x, int n) {
if(x==0) return 0;
long b = n;
double res = 1.0;
if(b<0){
x = 1 / x;
b = -b;
}
while(b>0){
if((b&1)==1) res *= x;
x *= x;
b >>= 1;
}
return res;
}
}
最新文章
- LeetCode Coin Change
- 15.6.2 Configuring the Merge Threshold for index pages[innodb]
- python数据结构与算法——栈
- velocity 显示List和Map方法
- mysql导出查询结果到csv方法
- json换行符的处理
- SeuRain的归来
- [转载]SQL字符串处理函数大全
- ReentrantLock与synchronized的差别
- 【精品】Android游戏类源码大集合
- Boost 1.61.0 Library Documentation
- 使用OGG&;quot;Loading data from file to Replicat&;quot;的方法应该注意的问题:replicat进程是前台进程
- 学习GDI+ (1)
- 3分钟教你做一个iphone手机浏览器
- 配置ssh无密钥登陆
- [Swift]LeetCode399. 除法求值 | Evaluate Division
- ios 适配iOS11&;iPhoneX的一些坑
- C++的静态联编和动态联编
- UNIX环境编程学习笔记(10)——文件I/O之硬链接和符号链接
- JS中的getter与setter