Sword refers to offer interview question 11, and sword refers to offer question 11
Question:
Implement the double Power (double base, int exponent) function to calculate the Power of base's exponent. Do not use library functions, and do not need to consider large numbers.
#include<iostream>using namespace std;double PowerUnsigned(double base ,unsigned int exponent){ if (exponent == 0) return 1; if (exponent == 1) return base; double result = PowerUnsigned(base,exponent>>1); result *= result; if ((exponent & 0x1) == 1) result = result*base; return result;}bool equal(double num1,double num2){ if ((num1 - num2 > -0.00000001) && (num1 - num2 < 0.00000001)) return true; else return false;}double Power(double base, int exponent){ if (equal(base, 0) && exponent < 0) throw exception("Invaild value"); unsigned int absExponent = static_cast<unsigned int>(abs(exponent)); double result = PowerUnsigned(base, absExponent); if (exponent < 0) result = 1 / result; return result;}int main(){ double v1 = 2; int v2 = -1; cout<<Power(v1,v2); return 0;}
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.