zoukankan      html  css  js  c++  java
  • leetcode50- Pow(x, n)- medium

    Implement pow(xn).


    Example 1:

    Input: 2.00000, 10
    Output: 1024.00000
    

    Example 2:

    Input: 2.10000, 3
    Output: 9.26100
    

    1.二分法递归。 把pow(x,n)拆解为pow(x,n/2) 的平方,这样就能做到logN了。

    2.折半。while循环每次计数要乘的部分n折半,数据处理就是自己乘自己,然后小心n是奇数的时候多乘一个x

    细节:1.n为奇数的时候要多乘一个x。2.n是负数的时候先作为正数处理,最后返回1/result 3.小心输入n = -21...8最小数的情况,反转会溢出,可以转换为1/x * pow(x, -21..7)

    简洁实现

    public class Solution {
        /*
         * @param x: the base number
         * @param n: the power number
         * @return: the result
         */
        public double myPow(double x, int n) {
            // write your code here
            if (n == 0) {
                return 1.0;
            } else if (n < 0) {
                return 1 / myPow(x, -n - 1) / x;
            } else if (n % 2 == 0) {
                return myPow(x * x, n / 2);
            } else {
                return x * myPow(x, n - 1);
            }
        }
    }
    class Solution {
        public double myPow(double x, int n) {
            
            if (n == 0) {
                return 1;
            }
            if (n == Integer.MIN_VALUE) {
                return 1 / x * myPow(x, n + 1);
            }
            
            boolean isNegative = false;
            if (n < 0) {
                n = -n;
                isNegative = true;
            }
    
            double result = myPow(x, n / 2);
            result = result * result;
            if (n % 2 == 1) {
                result = result * x;
            }
            
            if (isNegative) {
                return 1 / result;
            } else {
                return result;
            }
        }
    }

    2.折半法

    class Solution {
        public double myPow(double x, int n) {
            
            if (n == 0) {
                return 1;
            }
            if (n == Integer.MIN_VALUE) {
                return 1 / x * myPow(x, n + 1);
            }
            
            boolean isNegative = false;
            if (n < 0) {
                n = -n;
                isNegative = true;
            }
    
            double result = myPow(x, n / 2);
            result = result * result;
            if (n % 2 == 1) {
                result = result * x;
            }
            
            if (isNegative) {
                return 1 / result;
            } else {
                return result;
            }
        }
    }
     
  • 相关阅读:
    max-points-on-a-line
    evaluate-reverse-polish-notation
    minimum-depth-of-binary-tree
    ML&MLDS笔记:偏差 vs 方差
    机器人的运动范围
    矩阵中的路径
    滑动窗口的最大值
    数据流中的中位数
    1.微服务架构设计(英文-起源)
    5.如何复制一个文件(编程)
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7814953.html
Copyright © 2011-2022 走看看