题目描述
给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
1 class Solution { 2 public: 3 double Power(double base, int exponent) { 4 double ans = 1.0; 5 double t = base; 6 int flag = 0; 7 if(exponent == 0) 8 { 9 return 1; 10 } 11 else if(exponent < 0) 12 { 13 exponent = -exponent; 14 flag = 1; 15 } 16 while(exponent) 17 { 18 if(exponent & 1) 19 { 20 ans *= t; 21 } 22 t *= t; 23 exponent >>= 1; 24 } 25 if(flag) 26 { 27 return 1 / ans; 28 } 29 else 30 { 31 return ans; 32 } 33 } 34 };