题目
实现函数double Power(double base, int exponent),求base的exponent次方。不得使用库函数,同时不需要考虑大数问题。
示例 1:
1
2 输入: 2.00000, 10
输出: 1024.00000示例 2:
1
2 输入: 2.10000, 3
输出: 9.26100示例 3:
1
2
3 输入: 2.00000, -2
输出: 0.25000
解释: 2-2 = 1/22 = 1/4 = 0.25说明:
- -100.0 < x < 100.0
- n 是 32 位有符号整数,其数值范围是 [−231, 231 − 1] 。
注意:本题与主站 50 题相同:https://leetcode-cn.com/problems/powx-n/
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shu-zhi-de-zheng-shu-ci-fang-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
没接触过循环快速幂,自己写的二分递归实现:
1 | class Solution { |
关于把/2
优化为>>1
,要注意:对负数进行移位运算左侧补1,且负数以补码形式存在于内存中,结果是(-3)>>1
的结果为-2
。
其次,运算时可以先将幂次按照正数计算,最后取倒数。值得注意的是需要考虑底数为0的特殊情况。
1 | class Solution { |
还有一个坑,int 的表示范围为 $[-2^{31},\ 2^{31}-1]$,当 n 取边界值时不能对其直接取负数。