方法一:暴力法

  • 注意输入的指数的正负

    public class Solution {
      public double Power(double base, int exponent) {
          if(exponent == 0)
              return 1;
          if(exponent < 0)
          {
              base = 1/base;
          }
          int len = exponent > 0?exponent:-exponent;
          double res = base;
          for(int i = 0; i < len-1; i++)
          {
              res *= base;
          }
          return res;
    }
    }

    方法二:快速冪

  • 位运算的优先级低于==

  • java运算符优先级

    public class Solution {
      public double Power(double base, int exponent) {
          int len = exponent >= 0 ? exponent : -exponent;
          double res = 1.0;
          while(len != 0)
          {
              if((len&1)!=0)  //用位运算判断一个数的奇偶性
              {
                  res *= base;
    
              }
              base *= base;
              len = len>>>1;
          }
          return exponent >= 0 ? res : 1/res;
    }
    }