ZhengXingchi / ZhengXingchi.github.io

Apache License 2.0
0 stars 0 forks source link

剑指offer(12)数值的整数次方 #53

Open ZhengXingchi opened 4 years ago

ZhengXingchi commented 4 years ago

常规求幂

   function mi(a, b) {
      let r = 1
      while (b--) {
        r *= a
      }
      return r
    }
    console.log(mi(2, 4))

快速求幂


    function quick(a, b) {
      let r = 1
      let base = a
      while (b) {
        if (b & 1) {
          r *= base
        }
        base *= base
        b = b >> 1
      }
      return r
    }
    console.log(quick(2, 4))
ZhengXingchi commented 4 years ago

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

    function power(base, exponent) {
      let res = 1,
        n;
      if (exponent > 0) {
        n = exponent;
      } else if (exponent < 0) {
        if (!base) throw new Error('分母不能为0')
        n = -exponent
      } else {
        return 1
      }

      while (n) {
        if (n & 1) {
          res *= base
          base *= base
        }
        n = n >> 1
      }
      return exponent > 0 ? res : 1 / res

    }