实现函数double Power(double base, int exponent),求base的exponent次方。不得使用库函数,同时不需要考虑大数问题。
示例 1:
输入: 2.00000, 10
输出: 1024.00000
示例 2:
输入: 2.10000, 3
输出: 9.26100
示例 3:
输入: 2.00000, -2
输出: 0.25000
解释: 2-2 = 1/22 = 1/4 = 0.25
说明:
-100.0 < x < 100.0
n 是 32 位有符号整数,其数值范围是 [−231, 231 − 1] 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shu-zhi-de-zheng-shu-ci-fang-lcof
本题采用快速幂法,将x^n分n为奇数和偶数进行不同计算,可实现时间复杂度O(logn)的解法,同时由于在C语言将负整数转换为正整数时,可能会有溢出情况,通过unsigned int m = (unsigned int)n转换排除溢出问题。
double myPow(double x, int n){
double res;
if(x == 0)
return 0;
unsigned int m = (unsigned int)n;
if(n < 0)
{
m = -m;
x = 1 / x;
}
res = 1;
while(m)
{
if(m & 1)
res *= x;
x *= x;
m >>= 1;
}
return res;
}
#include
double myPow(double x, int n);
int main(void)
{
printf("x = 2.1, n = 0, res = %lf\n", myPow(2.1, 0));
printf("x = 2.1, n = 3, res = %lf\n", myPow(2.1, 3));
printf("x = 2.1, n = -3, res = %lf\n", myPow(2.1, -3));
printf("x = -2.1, n = 3, res = %lf\n", myPow(-2.1, 3));
printf("x = -2.1, n = -3, res = %lf\n", myPow(-2.1, -3));
printf("x = -2.1, n = 0, res = %lf\n", myPow(-2.1, 0));
printf("x = 0.0, n = 3, res = %lf\n", myPow(0.0, 3));
printf("x = 0.0, n = -3, res = %lf\n", myPow(0.0, - 3));
printf("x = 0.0, n = 0, res = %lf\n", myPow(0.0, 0));
return 0;
}