当前位置:网站首页>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
边栏推荐
- Detailed AST abstract syntax tree
- leetcode 448. Find All Numbers Disappeared in an Array 找到所有数组中消失的数字(简单)
- 软件测试基本流程有哪些?权威的第三方软件检测机构推荐
- leetcode 461. 汉明距离
- Use ControlTemplate or Style from resource file in WPF .cs and find the control
- EasyCVR平台海康摄像头语音对讲功能配置的3个注意事项
- 花 30 美金请 AI 画家弄了个 logo,网友:画得非常好,下次别画了!
- JMeter笔记5 |Badboy使用和录制
- leetcode 2119. 反转两次的数字
- Auto.js脚本程序打包
猜你喜欢
tRNA-m5C转运RNA(tRNA)修饰5-甲基胞嘧啶(m5C)|tRNA修饰m1Am2A (2-methyladenosine)
【飞控开发高级教程4】疯壳·开源编队无人机-360 度翻滚
【微信小程序2】事件传参与数据同步[03]
Node version switching tool NVM and npm source manager nrm
安装anaconda并创建虚拟环境
若依集成easyexcel实现excel表格增强
abs()、fabs() 和 labs() 的区别
消除对特权账户的依赖使用Kaniko构建镜像
tRNA甲基化偶联3-甲基胞嘧啶(m3C)|tRNA-m3C (3-methylcy- tidine)
codeforces:C. Maximum Subrectangle【前缀和 + 贪心 + 最小子数组和】
随机推荐
极验深知v2分析
LeetCode 622. 设计循环队列
华为设备配置VRRP负载分担
EMQX Newsletter 2022-07|EMQX 5.0 正式发布、EMQX Cloud 新增 2 个数据库集成
Detailed AST abstract syntax tree
若依集成browscap读取浏览器用户代理
alicloud3搭建wordpress
Detailed steps for tensorflow-gpu2.4.1 installation and configuration
RNA-ATTO 390|RNA-ATTO 425|RNA-ATTO 465|RNA-ATTO 488|RNA-ATTO 495|RNA-ATTO 520近红外荧光染料标记核糖核酸RNA
深入理解JVM-内存结构
ARMuseum
xss.haozi练习通关详解
Leetcode sword refers to Offer 15. 1 in the binary number
ES6--剩余参数
leetcode 268. 丢失的数字(异或!!)
Why BI software can't handle correlation analysis
【leetcode】剑指 Offer II 008. 和大于等于 target 的最短子数组(滑动窗口,双指针)
【STM32】标准库-自定义BootLoader
【飞控开发高级教程3】疯壳·开源编队无人机-定高、定点、悬停
若依集成easyexcel实现excel表格增强