当前位置:网站首页>【myPow,2次幂,3次幂..代码实现】
【myPow,2次幂,3次幂..代码实现】
2022-08-03 05:11:00 【tt142】
pow的返回值和参数都是double类型,那如何自定义函数达到一样效果呢
double myPow(double x, int n) {
if (n == 0)
return 1;
if (n == -1)
return 1 / x;
if (n & 1) //n&1用来判断n的最后一位
return myPow(x * x, n >> 1) * x; //是1就说明 n是奇数,n>>1相当于n-=2
else return myPow(x * x, n >> 1); //是0说明n是偶数
}//巧妙运用递归简化计算2次幂
2的次幂
bool isPowerOfTwo(int n) {
return n > 0 && (n & -n) == n; //n必须大于零,2的次幂二进制序列只有一个1和自身&一定还是本身
}
或者
bool isPowerOfTwo(int n) {
return (n > 0) && (1 << 30) % n == 0; 1<<30是2次幂中的最大,如果%n是0,说明n只有一个因子2
}
或者 好处在于3 4 的次幂直接改数字
bool isPowerOfThree(int n) {
if (n <= 0)
return false;
if (n == 1)
return true;
long long ans = 1;
while (1)
{
ans *= 2;
if (ans == n)
return true;
if (ans > n)
return false;
} return false;
}
三次幂或者四次幂..
3的次幂
bool isPowerOfThree(int n) {
if (n <= 0)
return false;
if (n == 1)
return true;
long long ans = 1;
while (1)
{
ans *= 3;
if (ans == n)
return true;
if (ans > n)
return false;
} return false;
}
边栏推荐
猜你喜欢

js implements a bind function

Common fluorescent dyes to modify a variety of groups and its excitation and emission wavelength data in the data

junit总结

Redis常用命令

13.< tag-动态规划和回文字串>lt.647. 回文子串 + lt.516.最长回文子序列

web安全-SSTI模板注入漏洞

High availability, two locations and three centers

Kaggle(四)Scikit-learn

第四次培训

typescript45-接口之间的兼容性
随机推荐
C# async and multithreading
快速上手 Mockito 单元测试框架
IO流及其操作
shell script loop statement
Fluorescent marker peptides FITC/AMC/FAM/Rhodamine TAMRA/Cy3 / Cy5 / Cy7 - Peptide
Gradle的安装配置
Pr第三次培训笔记
Pr第四次培训笔记
CAD有生僻字如何打出来、如何提交软件相关问题或建议?
反射注解基础
junit总结
Redis常用命令
Installation of Apache DolphinScheduler version 2.0.5 distributed cluster
Pr第二次培训笔记
High availability, two locations and three centers
如何不耍流氓的做运维之-SHELL脚本
typescript46-函数之间的类型兼容性
breed Web刷机升级详细教材修正编译器固件说明_itkeji.top
Kaggle 入门(Kaggle网站使用及项目复现)
阿里云对象存储oss私有桶生成链接