LeetCode Featured TOP interview questions (Java realization) - Pow (x, n)

One, Title Description

1.1 Topic
  • Pow(x, n)

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

  • Example 1:

输入: 2.00000, 10
输出: 1024.00000
  • Example 2:
输入: 2.10000, 3
输出: 9.26100
  • Example 3:
输入: 2.00000, -2
输出: 0.25000
解释: 2-2 = 1/22 = 1/4 = 0.25
  • Description:
    -100.0 <X <100.0
    n-32-bit signed integer, which is the numerical range [-231 231--1].
1.2 knowledge points
  • Binary search
1.3 topic Link

Second, problem-solving ideas

2.1 self-development ideas

  This question I think for the method is simple recursion, by merging operations to reduce the overall amount of computation the very beginning, but in the use of recursion is always a test case to make life difficult, so for an idea, all the problems can be recursive use a loop to solve, so the use of recycled again to resolve.

  Specific solutions thinking is merging of ideas, it can be said binary thinking to find, namely through continuous merging complex used to reduce the amount of calculation should be noted that because of the problem of n may go negative, so when setting the cut-off conditions Note that a cut-off approach is first to take the absolute value of n, is determined and then unified i> 0, and another idea can be directly determined by i! = 0 is achieved terminated. When we calculated according to the unified operation to a positive power, then the power is determined according to the sign of the final result of the need for return taking the inverse operation.

Third, the implementation code

3.1 to achieve self-development
class Solution {
    public double myPow(double x, int n) {
        
        double res = 1.0;
        // 也可使用 abs 函数将 n 取正后判断 i > 0
        for(int i = n; i != 0; i /= 2){ 
            if(i % 2 != 0) res *= x;
            x *= x;
        }
        return n < 0 ? 1/res : res;
    }
}
Published 244 original articles · won praise 32 · views 30000 +

Guess you like

Origin blog.csdn.net/qq_40697071/article/details/103948089