1. 程式人生 > >【劍指offer】16、數值的整數次方

【劍指offer】16、數值的整數次方

urn bsp unsigned info 直接 signed http 指數 ret

題目

實現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)); } };

【劍指offer】16、數值的整數次方