标签:unsigned 循环 lang https == 输出 ble 复杂度 offer
实现函数double Power(double base, int exponent),求base的exponent次方。不得使用库函数,同时不需要考虑大数问题。
示例 1:
输入: 2.00000, 10
输出: 1024.00000
示例?2:
输入: 2.10000, 3
输出: 9.26100
示例?3:
输入: 2.00000, -2
输出: 0.25000
解释: 2-2 = 1/22 = 1/4 = 0.25
说明:
如果暴力求解,即循环将 x 累乘 n 次则超时,考虑到求一个数 n 次方,比如n为8,则只需在x的4次方的基础上再平方一次,依次类推,可得如下公式:
几种特殊case:
时间复杂度:O(logn)
空间复杂度:O(1)
class Solution {
public:
double myPow(double x, int n) {
double res = 1.0;
if (n == 0) return res;
unsigned int t = abs(n); // 负数最小值溢出
res = helper(x, t);
if (n < 0) res = 1 / res;
return res;
}
double helper(double x, unsigned int n) {
if (n == 0) return 1;
if (n == 1) return x;
double res = helper(x, n >> 1);
res *= res;
if (n & 0x1 == 1) res *= x; // n 为奇数
return res;
}
};
标签:unsigned 循环 lang https == 输出 ble 复杂度 offer
原文地址:https://www.cnblogs.com/galaxy-hao/p/12865505.html