剑指offer16数值的整数次方
Posted shiganquan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了剑指offer16数值的整数次方相关的知识,希望对你有一定的参考价值。
题目
实现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)); } };
以上是关于剑指offer16数值的整数次方的主要内容,如果未能解决你的问题,请参考以下文章