标签:c++ sig public base ret unsigned result amp 数值
给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
比如求2的32次方,先求出2的16次方,然后2^16 * 2^16
然后递归求2^16,如果次方为奇数,则再乘一个base
C++:
1 class Solution { 2 private: 3 bool invalidInput = false ; 4 public: 5 bool Equal(double num1 , double num2){ 6 if ((num1-num2)<0.0000001 && (num1-num2)>-0.0000001) 7 return true ; 8 else 9 return false ; 10 } 11 12 double PowerWithUnsignedExponent(double base , int exponent){ 13 if (exponent == 0) 14 return 1 ; 15 if (exponent == 1) 16 return base ; 17 double result = PowerWithUnsignedExponent(base,exponent>>1) ; 18 result *=result ; 19 if (exponent&1) 20 result *= base ; 21 return result ; 22 } 23 24 double Power(double base , int exponent){ 25 bool invalidInput = false ; 26 if (Equal(base,0.0) && exponent < 0){ 27 invalidInput = true ; 28 return 0.0 ; 29 } 30 int absExponent = abs(exponent) ; 31 double result = PowerWithUnsignedExponent(base,absExponent) ; 32 if (exponent < 0) 33 result = 1.0/result ; 34 return result ; 35 } 36 };
标签:c++ sig public base ret unsigned result amp 数值
原文地址:https://www.cnblogs.com/mengchunchen/p/8915781.html