xiaomi

个人博客

小米的个人博客,欢迎交流


每天一道剑指offer:数值的整次方

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

代码

  • 解法1:
    public double Power(double base, int exponent) {
        double res = 1.0;
        if (exponent == 0) return res;
        if (exponent < 0) {
            base = 1.0 / base;
            exponent = -exponent;
        }
        for (int i = 0; i < exponent; i++) {
            res *= base;
        }
        return res;
    }
  • 解法2:
      public double Power(double base, int exponent) {
    
          double result = 1.0;
          if (exponent == 0) return result;
          if (exponent == 1) return base;
    
          int n = Math.abs(exponent);
          while (n != 0) {
              if ((n & 1) == 1) {
                  result *= base;
              }
              n >>= 1;
              base *= base;
          }
    
          if (exponent < 0) result = 1 / result * 1.0;
    
    
          return result;
      }
    
  • 解法3: ```java public double Power(double base, int exponent) { double result = 0.0; if (exponent == 0) return 1.0; if (exponent == 1) return base;

      int ex = Math.abs(exponent);
      result = Power3(base, ex >> 1);
      result *= result;
    
      if ((exponent & 1) == 1) result *= base;
    
      if (exponent < 0) result = 1 / result * 1.0;
      return result;   }
    

```