当前位置:网站首页>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
边栏推荐
猜你喜欢
【leetcode】剑指 Offer II 008. 和大于等于 target 的最短子数组(滑动窗口,双指针)
机器学习中专业术语的个人理解与总结(纯小白)
5 款漏洞扫描工具:实用、强力、全面(含开源)
ESP8266-Arduino编程实例-WS2812驱动
面试官:为什么 0.1 + 0.2 == 0.300000004?
微导纳米IPO过会:年营收4.28亿 君联与高瓴是股东
为什么 BI 软件都搞不定关联分析
List类的超详细解析!(超2w+字)
Li Mu hands-on learning deep learning V2-BERT fine-tuning and code implementation
单调栈及其应用
随机推荐
模板字符串概述
谁的孙子最多II
matplotlib画polygon, circle
Alexa染料标记RNA核糖核酸|RNA-Alexa 514|RNA-Alexa 488|RNA-Alexa 430
子结点的数量(2)
Li Mu hands-on learning deep learning V2-BERT fine-tuning and code implementation
力扣203-移除链表元素——链表
极验深知v2分析
友宏医疗与Actxa签署Pre-M Diabetes TM 战略合作协议
Auto.js脚本程序打包
leetcode 448. Find All Numbers Disappeared in an Array 找到所有数组中消失的数字(简单)
xss.haozi练习通关详解
抖音web逆向教程
2022.8.2
亚马逊云科技 Build On 2022 - AIot 第二季物联网专场实验心得
开源生态研究与实践| ChinaOSC
149. The largest number on a straight line, and check the set
【飞控开发高级教程4】疯壳·开源编队无人机-360 度翻滚
信使mRNA甲基化偶联3-甲基胞嘧啶(m3C)|mRNA-m3C
盲埋孔PCB叠孔设计的利与弊