题目链接:点击打开链接
题目大意:略
解题思路
相关企业
- 字节跳动
- 亚马逊(Amazon)
- 彭博(Bloomberg)
- 谷歌(Google)
- 微软(Microsoft)
- 优步(Uber)
- 高盛集团(Goldman Sachs)
- 苹果(Apple)
- 领英(LinkedIn)
AC 代码
- Java
// 解决方案(1)
// 模拟版
class Solution {
public double myPow(double x, int n) {
long maxn = n;
if (n == 0 || x == 1) return 1.0;
if (x == -1) return n % 2 == 0 ? 1.0 : -1.0;
if (n < 0 && -maxn > 50) return 0.0;
double res = 1.0;
boolean flag = false;
if (n < 0) {
n = -n;
flag = true;
}
while (n-- != 0) {
res *= x;
}
if (flag) {
res = 1.0 / res;
}
res = ((int)(res * 100000 + 0.5)) / 100000.0;
return res;
}
}
// 解决方案(2)
// 快速幂版
class Solution {
public double myPow(double x, int n) {
if(x == 0.0f) return 0.0d;
long b = n;
double res = 1.0;
if(b < 0) {
x = 1 / x;
b = -b;
}
while(b > 0) {
if((b & 1) == 1) res *= x;
x *= x;
b >>= 1;
}
return res;
}
}
- C++
class Solution {
public:
double myPow(double x, int n) {
if(x == 0.0f) return 0.0;
long b = n;
double res = 1.0;
if(b < 0) {
x = 1 / x;
b = -b;
}
while(b > 0) {
if((b & 1) == 1) res *= x;
x *= x;
b >>= 1;
}
return res;
}
};