当前位置:网站首页>【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;
}
边栏推荐
猜你喜欢
Apache DolphinScheduler版本2.0.5分布式集群的安装
[Harmony OS] [ARK UI] ETS context basic operations
Redis6学习笔记
数据分析 第一篇
深度学习入门之GRU
Newifi路由器第三方固件玩机教程,这个路由比你想的更强大以及智能_Newifi y1刷机_smzdm
idea使用@Autowired注解爆红原因及解决方法
js实现一个 bind 函数
【Biotin Azide|cas:908007-17-0】Price_Manufacturer
Ali cloud object storage oss private barrels to generate links
随机推荐
js implements a bind function
HarmonyOS应用开发第一次培训
Pr第二次培训笔记
web安全-SSTI模板注入漏洞
1095 解码PAT准考证 (25 分)(C语言)
Common lipophilic cell membrane dyes DiO, Dil, DiR, Did spectrograms and experimental procedures
Pr第三次培训笔记
1094 谷歌的招聘 (20 分)
1069 微博转发抽奖 (20 分)(C语言)
阿里云对象存储oss私有桶生成链接
Pr第四次培训笔记
IO流及其操作
1089 狼人杀-简单版 (20 分)
Odps temporary query can write SQL, turned out to a named?
Flask的简单介绍及使用方法简介
web安全-命令执行漏洞
typescript49-交叉类型
【Harmony OS】【ARK UI】ets use startAbility or startAbilityForResult to invoke Ability
【转】最小描述长度准则MDL(Minimun Description Length)
《录取通知》 观后感