• 0050. Pow(x, n) (M)


    Pow(x, n) (M)

    题目

    mplement pow(x, n), which calculates x raised to the power n ((x^n)).

    Example 1:

    Input: 2.00000, 10
    Output: 1024.00000
    

    Example 2:

    Input: 2.10000, 3
    Output: 9.26100
    

    Example 3:

    Input: 2.00000, -2
    Output: 0.25000
    Explanation: 2-2 = 1/22 = 1/4 = 0.25
    

    Note:

    • -100.0 < x < 100.0
    • n is a 32-bit signed integer, within the range ([−2^{31}, 2^{31} − 1])

    题意

    手动实现乘方运算。

    思路

    方法参考快速幂(二分幂)


    代码实现

    Java

    递归

    class Solution {
        public double myPow(double x, int n) {
            if (Double.compare(x, 1.0) == 0) {
                return 1.0;
            }
            
            double pow = binaryPow(x, n);
            return n < 0 ? 1 / pow : pow;
        }
    
        private double binaryPow(double x, int n) {
            if (n == 0) {
                return 1;
            }
    
            double temp = binaryPow(x, n / 2);
            return n % 2 == 0 ? temp * temp : temp * temp * x;
        }
    }
    

    迭代

    class Solution {
        public double myPow(double x, int n) {
            if (Double.compare(x, 1.0) == 0) {
                return 1.0;
            }
    
            double pow = 1.0;
            // 无论正数负数,除以2相当于将其绝对值的二进制右移一位
            for (int i = n; i != 0; i /= 2) {
                // 无论正数负数,不是偶数说明其绝对值二进制末位为1
                if (i % 2 != 0) {
                    pow *= x;
                }
                x *= x;
            }
    
            return n < 0 ? 1 / pow : pow;
        }
    }
    

    JavaScript

    递归

    /**
     * @param {number} x
     * @param {number} n
     * @return {number}
     */
    var myPow = function (x, n) {
      if (n === 0) {
        return 1
      }
    
      let pow = myPow(x, Math.trunc(n / 2))
      if (n % 2 === 0) {
        return pow * pow
      } else if (n > 0) {
        return pow * pow * x
      } else {
        return (pow * pow) / x
      }
    }
    

    迭代

    /**
     * @param {number} x
     * @param {number} n
     * @return {number}
     */
    var myPow = function (x, n) {
      let pow = 1
      let isMinus = n < 0
      while (n !== 0) {
        if (n % 2 !== 0) {
          pow *= x
        }
        x *= x
        n = Math.trunc(n / 2)
      }
      return isMinus ? 1 / pow : pow
    }
    
  • 相关阅读:
    在本地连接服务器上的mysql数据库
    js提取字符串中的数值
    下载安装mysql
    git最基础操作二(clone)
    点击页面出现富强、民主
    解决wepacke配置postcss-loader时autoprefixer失效问题
    li之间产生的间隙问题的解决方法
    webpack简单体验
    apply、call和bind
    remote Incorrect username or password ( access token)问题解决
  • 原文地址:https://www.cnblogs.com/mapoos/p/13217122.html
Copyright © 2020-2023  润新知