当前位置:网站首页>Leetcode 16. Numerical integral power (power + fast recursive/iteration)
Leetcode 16. Numerical integral power (power + fast recursive/iteration)
2022-08-03 20:12:00 【Luna who can program】
实现 pow(x, n) ,即计算 x 的 n 次幂函数(即,xn).不得使用库函数,同时不需要考虑大数问题.
示例 1:
输入:x = 2.00000, n = 10
输出:1024.00000
示例 2:
输入:x = 2.10000, n = 3
输出:9.26100
示例 3:
输入:x = 2.00000, n = -2
输出:0.25000
解释:2-2 = 1/22 = 1/4 = 0.25
提示:
-100.0 < x < 100.0
-231 <= n <= 231-1
-104 <= xn <= 104
思路:
快速幂+递归
class Solution {
public:
double myQuick(double x,long long k){
if(k==0)
return 1.0;
double y=myQuick(x,k/2);
return k%2==0 ? y*y : y*y*x;
}
double myPow(double x, int n) {
long long N=n;
return N>0 ? myQuick(x,N) : 1.0/myQuick(x,-N);
}
};
快速幂+迭代:
class Solution {
public:
double myPow(double x, int n) {
if(n==0)
return 1.0;
if(x==0)
return 0;
double ans=1.0;
long long b=n; //因为intWhen it is a positive number, the complement is itself,If it is negative number's complement,Need to add after changing the sign1,如果传进来的是(-2)的32次方,It will be exceeded after it is reversedint,所以要用long longto expand the type
if(n<0){
x=1/x; //Here is the direct reciprocal first,Calculate the countdown againn次方
b=-b;
}
while(b>0){
if(b&1==1) //如果b最后一位为1,Just multiply in the final result,是0It doesn't count in the results
ans*=x;
x*=x;
b>>=1; //The right shift operator can be thought of as deleting the last bit,Remove the last one in the low order,高位正数补0,负数补1
}
return ans;
}
};
You can see the details of the left shift and right shift operations:Algorithms for left shift and right shift
边栏推荐
- PHP according to the longitude and latitude calculated distance two points
- 不知道这4种缓存模式,敢说懂缓存吗?
- 机器学习中专业术语的个人理解与总结(纯小白)
- Use ControlTemplate or Style from resource file in WPF .cs and find the control
- ES6解构赋值--数组解构及对象解构
- 力扣59-螺旋矩阵 II——边界判断
- 【飞控开发高级教程3】疯壳·开源编队无人机-定高、定点、悬停
- 剑指 Offer II 044. 二叉树每层的最大值-dfs法
- 单调栈及其应用
- Solidity智能合约开发 — 4.1-合约创建和函数修饰器
猜你喜欢
随机推荐
EasyCVR平台海康摄像头语音对讲功能配置的3个注意事项
2022.8.2
MapReduce介绍及执行过程
Kubernetes资源编排系列之三: Kustomize篇 作者 艄公(杨京华) 雪尧(郭耀星)
李沐动手学深度学习V2-自然语言推断与数据集SNLI和代码实现
若依集成browscap读取浏览器用户代理
JS 内置构造函数 扩展 prototype 继承 借用构造函数 组合式 原型式creat 寄生式 寄生组合式 call apply instanceof
leetcode 072. Finding Square Roots
Detailed AST abstract syntax tree
ES6--剩余参数
后台图库上传功能
Pytorch GPU 训练环境搭建
In-depth understanding of JVM-memory structure
【leetcode】剑指 Offer II 007. 数组中和为 0 的三个数(双指针)
pytorch框架实现老照片修复功能详细演示(GPU版)
剑指 Offer II 044. 二叉树每层的最大值-dfs法
化算力为战力:宁夏中卫的数字化转型启示录
EMQX Newsletter 2022-07|EMQX 5.0 正式发布、EMQX Cloud 新增 2 个数据库集成
【HiFlow】经常忘记签到怎么办?使用腾讯云场景连接器每天提醒你。
Go语言为任意类型添加方法







![【微信小程序2】事件传参与数据同步[03]](/img/d9/73004e6edf800c583231a94dfbd878.png)

