Leetcode50.Pow(x, n)

Title Description

Achieve pow (x, n), i.e., a function of n-th power of x.

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
explained: 2 2 2^{-2} = 1 / 2 2 1/2^{2} = 1/4 = 0.25

Description:

  • -100.0 < x < 100.0
  • n is a 32-bit signed integer, which is the numerical range [-231 231--1].

answer

Violence (java)

Thinking feeling to do so, then it is entirely up to find a variety of special circumstances. And algorithm time out. . Down is to plan a complete solution to a problem (x
Note:


//对x 和 n 的值进行特殊处理
        //最小值:Integer.MIN_VALUE= -2147483648 (-2的31次方)
        //最大值:Integer.MAX_VALUE= 2147483647  (2的31次方-1)
        //这里需要使用long类型,因为如果传入的n = -2147483648; 那么转成正数就丢失,所以要使用long
        long N = n;
        if(N < 0){
            N = -N;
            x = 1/x;
        }
        return  pow(x,N);
class Solution {
    public double myPow(double x, int n) {
        long N = n;
        if (N < 0) {
            x = 1 / x;
            N = -N;
        }
        double ans = 1;
        for (long i = 0; i < N; i++)
            ans = ans * x;
        return ans;
    }
};

Complexity Analysis

  • time complexity: THE ( N ) O (N)
  • Space complexity: THE ( 1 ) O (1)

Divide and Conquer (java)

Idea: with the idea of ​​partition, the calculation requires a step by step two. Note that the last of the merger.

class Solution {
    public double ans(double x, int n) {
        if (n == 0) return 1.0;
        double result = ans(x, n / 2);
        if (n % 2 == 0) {
            return result * result;
        } else {
            return result * result * x;
        }
    }
    public double myPow(double x, int n) {
        if (n >= 0) return ans(x, n);
        double result;
        int N = - n;
        result = ans(x, N);
        result = 1.0 / result;
        return result;
    }
}
  • time complexity: THE ( log N ) O(\log N)
  • Space complexity: THE ( log N ) O(\log N)
Published 43 original articles · won praise 20 · views 1442

Guess you like

Origin blog.csdn.net/Chen_2018k/article/details/105061906