剑指offer——数值的整数次方

数值的整数次方

给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方

public class Solution {
    public double Power(double base, int exponent) {
        if(exponent == 0) {
            return 1;
        }
        if(exponent > 0){
            return PowerPos(base, exponent);
        }else{
            return 1/PowerPos(base, -1 * exponent);
        }
  }
    public double PowerPos(double base, int exponent){
        if(exponent == 0) return 1;
        return base * this.PowerPos(base, exponent - 1);
    }
}

  

 

 

别人的方法:利用位运算

class Solution {
public:
    double Power(double base, int exponent) {
        long long p = abs((long long)exponent);
      double r = 1.0;
        while(p){
            if(p & 1) r *= base;
            base *= base;
            p >>= 1;
        }
        return exponent < 0 ? 1/ r : r;
    }
};

  

 

posted @ 2018-03-09 10:26  SkyeAngel  阅读(143)  评论(0编辑  收藏  举报