Pow(x, n)
Implement pow(x, n), which calculates x raised to the power n (xn).
Example 1:
1 | Input: 2.00000, 10 |
Example 2:
1 | Input: 2.10000, 3 |
Example 3:
1 | Input: 2.00000, -2 |
Note:
- -100.0 < x < 100.0
- n is a 32-bit signed integer, within the range [−231, 231 − 1]
思路:首先能想到最原始的方法,就是利用求一个数的n次方的公式。代码如下:
1 | class Solution { |
该方法虽然正确,但是运行超时。
在网上看到一个人利用类似二分法的思想,减少了乘法的使用次数。
代码如下:
1 | package irisqp.leetcode; |