*************
C++
topic: 50. Pow(x, n) - 力扣(LeetCode)
*************
Give the topic an inspection.
![]() |
Today is a good day because I have done all day job just in the past few seconds. And I have time to have some fun in here.
pow(x, n) means the number of x is n. so the code can be written as follow.
int result = 1;
if ( int i = 0; i < n; i++)
{
result = result * x;
}
let's give it a try.
class Solution {
public:
double myPow(double x, int n) {
// 用于存储结果
double result = 1;
// 开始循环
for (int i = 0; i < n; i++)
{
result = result * x;
}
return result;
}
};
![]() |
really nice. We have two cases are passed.
check the sample, if x is negative, then should play some mathematic tricks.
class Solution {
public:
double myPow(double x, int n) {
// 用于存储结果
double result = 1;
double help = 1;
// 开始循环
if (n > 0) // 幂是正的
{
for (int i = 0; i < n; i++)
{
result = result * x;
}
}
else if (n == 0) // 任何数的0次幂是1
{
return 1;
}
else // 幂是负的结果得是倒数
{
n = - n;
for(int i = 0; i < n; i++)
{
help = help * x;
result = 1 / help;
}
}
return result;
}
};
![]() |
need a smarter way to figure it out.
x is a static variable while n can be splitted.
x^n = (x^(n/2))^2 当 n 为偶数时
x^n = x*(x^(n/2))^2 当 n 为奇数时
Then dichotomy comes to me.
n = n / 2;
lets try the code.
class Solution {
public:
double myPow(double x, int n) {
if (n < 0)
{
x = 1 / x;
n = -n;
}
// result用来存储结果
double result = 1;
while (n > 0)
{
if (n % 2 == 1) // 如果幂是奇数
{
result = result * x;
}
x = x * x; // x²,二分法减少循环次数
n = n / 2; //向下取整,1.38 -> 1
}
return result;
}
};
![]() |
the minimum of the type int is -2147483648; I should know this.
type long long can fix it.
class Solution {
public:
double myPow(double x, int n) {
long long nn = n;
if (n < 0)
{
x = 1 / x;
nn = -nn;
}
// result用来存储结果
double result = 1;
while (nn > 0)
{
if (nn % 2 == 1) // 如果幂是奇数
{
result = result * x;
}
x = x * x; // x²,二分法减少循环次数
nn = nn / 2; //向下取整,1.38 -> 1
}
return result;
}
};
![]() |
Have a good day.





617

被折叠的 条评论
为什么被折叠?



