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

Redis常用命令

Talking about GIS Data (6) - Projected Coordinate System

shell script loop statement

内部类、static关键字、final

接口和抽象

typescript39-class类的可见修饰符

Ali cloud object storage oss private barrels to generate links

typescript49-交叉类型

嵌入式-I2C-物理电路图

Common fluorescent dyes to modify a variety of groups and its excitation and emission wavelength data in the data
随机推荐
Alienware上线首个数字时装AR试穿体验
js implements a bind function
typescript43-类型兼容性说明
三角形个数
Installation of Apache DolphinScheduler version 2.0.5 distributed cluster
【Biotin Azide|cas:908007-17-0】Price_Manufacturer
1059 C语言竞赛 (20 分)(C语言)
ss-4.1-1个eurekaServer+1个providerPayment+1个consumerOrder
1094 谷歌的招聘 (20 分)
接口和抽象
1095 解码PAT准考证 (25 分)(C语言)
Get the Ip tool class
Kaggle 入门(Kaggle网站使用及项目复现)
Common fluorescent dyes to modify a variety of groups and its excitation and emission wavelength data in the data
PotPlayer实现上班摸鱼电视自由
1089 狼人杀-简单版 (20 分)
ss-3.工程重构
飞机大战完整版
3. 无重复字符的最长子串
Djiango第二次培训