算法:求数的幂次方powx-n

说明

地址: https://leetcode.com/problems/powx-n/

Implement pow(x, n), which calculates x raised to the power n (xn).

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^311]

算法分析

  1. 这里用到的解决思路为二分法,比如2的10次方,等价于4的5次方,等价于4*(4的4次方),等价于4*(16的2次方),等价于4*(256的1次方).
  2. 需要考虑n的几个值
  • n == 0 返回1;
  • n == 1 返回x;
  • n == -1 x就要用x分之一, 并且n需要转为-n,同时需要考虑越界问题,解决为提取出多一个1/x, 公式为1/x * pow(1/x, -(n + 1)

递归求解

public double myPow(double x, int n) {
    if (n < 0) {
      // consider -n overflow
      return 1/x * myPow(1/x, -(n + 1));
    }
    if (n == 0) {
      return 1;
    }
    if (n == 1) {
      return x;
    }

    int halfN = n >> 1;
    return (n%2 == 0) ? myPow(x * x, halfN) : myPow( x * x, halfN) * x;
}

遍历求解

public double myPowWithIterate(double x, int n) {
    double result = 1;
    if (n < 0) {
      // consider -n overflow
      x = 1/x;
      n = -(n + 1);
      result = x;
    }

    while (n != 0) {
      if (n % 2 == 1) {
        result *= x;
        if (n == 1) {
          break;
        }
      }

      x = x * x;
      n = n >> 1;
    }

    return result;
}

代码下载

https://github.com/zgpeace/awesome-java-leetcode/blob/master/code/LeetCode/src/binarysearch/Powxn.java

发布了127 篇原创文章 · 获赞 12 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/zgpeace/article/details/103442013