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

安装IIS服务(Internet信息服务(Internet Information Services,简写IIS,互联网信息服务)

13.
lt.647. Palindromic substring + lt.516. Longest palindrome subsequence 
3. 无重复字符的最长子串

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

MCM box model modeling method and source analysis of atmospheric O3

typescript45-接口之间的兼容性

设计模式——组合模式、享元模式(Integer缓存)(结构型模式)

【Biotin Azide|cas:908007-17-0】Price_Manufacturer

【Harmony OS】【ARK UI】ets use startAbility or startAbilityForResult to invoke Ability

嵌入式-I2C-物理电路图
随机推荐
集合框架知识
Coordinate knowledge in digital twin campus scenarios
IO process thread -> thread -> day5
轨迹(形状)相似性判断与度量方法
js implements a bind function
Exception(异常) 和 Error(错误)区别解析
安装IIS服务(Internet信息服务(Internet Information Services,简写IIS,互联网信息服务)
Pr第四次培训笔记
vim命令
2022暑假牛客多校联赛第一场
Pr第二次培训笔记
阿里云对象存储oss私有桶生成链接
Redis常用命令
User password verification
1. 两数之和
-一尺之棰-
求因子数量
嵌入式-I2C-物理电路图
typescript47-函数之间的类型兼容性
Talking about GIS Data (6) - Projected Coordinate System