Topic describes
Given a float of type double base and an integer of type int exponent. I’m going to take base exponent.
Make sure that base and exponent are not both 0
Train of thought
You probably don’t have to think about it, just do it
Problems that might arise when doing the problem
Notice the return value, when base and exponent are equal to 0, respectively.
python
# -*- coding:utf-8 -*-
class Solution:
def Power(self, base, exponent):
# write code here
if base == 0:
return 0
if exponent == 0:
return 1
temp = 1
if exponent<0:
abs_exponent = -exponent
while abs_exponent:
temp *= base
abs_exponent -= 1
return 1/temp
else:
while exponent:
temp *= base
exponent -= 1
return temp
Copy the code
C++
class Solution {
public:
double Power(double base, int exponent) {
float res=1;
if(base==0 & exponent<=0)
return 0;
if(exponent<0)
{
res = 1;
for(int i=1; i<=-exponent; i++) res *= base; res=1/res; //res= pow(base,exponent); // pow, c++ exponential function // res=1/res;return res;
}
if(exponent>=0)
{
res = 1;
//for(int i=1; i<=exponent; i++) // res *= base; res= pow(base,exponent); // pow, an exponential function in c++returnres; }}};Copy the code