当前位置:网站首页>【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;
}
边栏推荐
猜你喜欢

2.ROS通信机制

Js学习笔记(四)

Detailed explanation of MOSN reverse channel

junit总结

Harmony OS Date ano UI 】 【 】 the basic operation

在树莓派上搭建属于自己的网页(1)

Kaggle(四)Scikit-learn

Build your own web page on raspberry pie (1)

【HMS core】【Ads Kit】Huawei Advertising——Overseas applications are tested in China. Official advertisements cannot be displayed

Newifi路由器第三方固件玩机教程,这个路由比你想的更强大以及智能_Newifi y1刷机_smzdm
随机推荐
minio下载文件乱码或者是一条横线
2. 两数相加
NotImplementedError: file structure not yet supported
1.ROS环境搭建与基础工作
Talking about GIS Data (5) - Geographic Coordinate System
高可用 两地三中心
Junit
-寻找鞍点-
阿凡提的难题
IO流及其操作
安装IIS服务(Internet信息服务(Internet Information Services,简写IIS,互联网信息服务)
Create a tree structure
生活原则。
Fluorescent marker peptides FITC/AMC/FAM/Rhodamine TAMRA/Cy3 / Cy5 / Cy7 - Peptide
2017-06-11 Padavan 完美适配newifi mini【adbyby+SS+KP ...】youku L1 /小米mini
Djiango第四次培训笔记
CAD有生僻字如何打出来、如何提交软件相关问题或建议?
HarmonyOS应用开发培训第二次作业
Ali cloud object storage oss private barrels to generate links
【HMS core】【Ads Kit】Huawei Advertising——Overseas applications are tested in China. Official advertisements cannot be displayed