NC264. 数值的整数次方
描述
示例1
输入:
2.00000,3
输出:
8.00000
示例2
输入:
2.10000,3
输出:
9.26100
示例3
输入:
2.00000,-2
输出:
0.25000
说明:
2的-2次方等于1/4=0.25C++ 解法, 执行用时: 2ms, 内存消耗: 404KB, 提交时间: 2021-05-31
class Solution { public: double Power(double base, int exponent) { double result = base; bool flag = false; if(!exponent) return 1; if(!base) return 0; if(exponent < 0) { exponent = -exponent; flag = true; } while(exponent-- > 1) result *= base; if(flag) result = 1/result; return result; } };
C++ 解法, 执行用时: 2ms, 内存消耗: 464KB, 提交时间: 2021-07-13
class Solution { public: double Power(double base, int exponent) { if(exponent==0){ return 1; } if(exponent<0){ base=1/base; exponent=-1*exponent; } return (exponent%2==0)?Power(base*base, exponent/2):base*Power(base*base, exponent/2); } };
C++ 解法, 执行用时: 2ms, 内存消耗: 468KB, 提交时间: 2021-07-17
class Solution { public: double Power(double base, int exponent) { if(base==0||base==1) return base; long a=exponent; if(a<0){ base=1/base; a=-a; } double ans=1; while(a){ if(a&1) ans*=base; base*=base; a>>=1; } return ans; } };
C++ 解法, 执行用时: 2ms, 内存消耗: 476KB, 提交时间: 2021-04-25
class Solution { public: double mypow(double base, int exponent){ double res = 1.0; while(exponent){ if(exponent & 1){ res *= base; } base *= base; exponent >>= 1; } return res; } double Power(double base, int exponent) { if(base == 0){ return 0; } if(exponent==0){ return 1; } if(exponent < 0) { base = 1.0 / base; exponent = -exponent; } return mypow(base, exponent); } };
C++ 解法, 执行用时: 2ms, 内存消耗: 484KB, 提交时间: 2021-05-03
class Solution { public: double Power(double base, int exponent) { double res = 1.0; if(exponent<0)base = 1.0/base,exponent*=-1; while(exponent) { if(exponent&1)res = res*base; base*= base; exponent>>=1; } return res; } };