タイトル説明
指数力の基盤を求めて、ダブルパワー(ダブルベース、int型の指数)を達成するための機能。多数の問題を検討する必要性を排除しながら、ライブラリ関数を使用しません。
示例 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
トピックリンク:https://leetcode-cn.com/problems/shu-zhi-de-zheng-shu-ci-fang-lcof
シンプルなソリューション - すべてのケースを考えて
class Solution {
public:
double myPow(double x, int n) {
if(n == 0 || x == 1.00) return 1.00;
int flag = 1;
if(n < 0){
n = -n;
flag = 0;
}
double rst = 1.00;
if(flag){
for(int i = 0 ; i < n;i ++)
rst *= x;
}else{
for(int i = 0; i < n; i++)
rst /= x;
}
return rst;
}
};
クイックパワー・ソリューション
$$
ベース=ベース^ *ベース2は
$$
$$
基礎^ 2 * 2 = ^基礎の基礎^ 4
$$
$$
同様*ベース4 ^^基地=ベース。4. 8 ^
$$
バイナリ指数に任意の非負指数分離のための、例えば
$$
ベースベース^ = ^ {11} 1 * 2 *ベースベース^^ 8。
$$
注:$ [11] {小数} = [1011] {}バイナリー$
高速電力テンプレートコード
// int pow(int base,int exp)
// 快速幂函数,返回 base^exp
// base 底数,exp指数
int pow(int base, int exp){
int ans = 1;
while(exp){
if(exp & 0x1){
ans *= base;//如果二进制的最后一位是1,则让ans = ans * base
}
base *= base;//第一次循环,base=base,第二次base = base^2...
exp >>= 1;
}
return ans;
}
この質問に答えます
class Solution {
public:
double myPow(double base, int n) {
double res = 1.0;
int exp = n;
while(exp){
if(exp & 0x01) res *= base;
base *= base;
exp /= 2;
}
return n>0?res:1.0/res;
}
};