题目
实现double Power(double base, int exponent),求base的exponent次方,不得使用库函数,同样需要考虑大数问题。
思路
题目意思很清楚,需要考虑情况周全。
1、若base=0,exp <= 0
2、若exp >= 0 , 直接return计算后的数值
若exp <= 0 ,return 计算后数值的倒数
注意定义是double,因此写代码时要写成0.0,1.0
class Solution { public: double Power(double base, int exponent) { if(base == 0.0 && exponent < 0) return 0.0; if (exponent >= 0){ return PowerWithUnsignedExponent(base, exponent); } else{ return (1.0 / PowerWithUnsignedExponent(base, -exponent)); } } double PowerWithUnsignedExponent(double base, unsigned int exponent){ if (exponent == 0) return 1.0; if (exponent == 1) return base; double result = PowerWithUnsignedExponent(base, exponent>>1); result *= result; if (exponent & 1) //判断指数是否为奇数 { result *= base; } return result; } };
改进
计算幂时可以用快速幂,思想如下:
class Solution { public: double Power(double base, int exponent) { if(base == 0.0 && exponent < 0) return 0.0; if (exponent >= 0){ return PowerWithUnsignedExponent(base, exponent); } else{ return (1.0 / PowerWithUnsignedExponent(base, -exponent)); } } double PowerWithUnsignedExponent(double base, unsigned int exponent){ if (exponent == 0) return 1.0; if (exponent == 1) return base; return (PowerWithUnsignedExponent(base, exponent>>1) * PowerWithUnsignedExponent(base, exponent>>1) * PowerWithUnsignedExponent(base, exponent%2)); } };
原文地址:https://www.cnblogs.com/shiganquan/p/9338962.html
时间: 2024-11-01 20:53:05