-
Notifications
You must be signed in to change notification settings - Fork 0
/
x的n次幂.java
43 lines (36 loc) · 847 Bytes
/
x的n次幂.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package com.algorithm.demo.interview;
/**
* 428 · x的n次幂
* 描述
* 实现 pow(x, n)。(n是一个整数)
*/
public class x的n次幂 {
public static void main(String[] args) {
}
/**
* @param x the base number
* @param n the power number
* @return the result
*/
public double myPow(double x, int n) {
// write your code here
boolean isNegative = false;
if (n < 0) {
x = 1 / x;
isNegative = true;
n = -(n + 1); // Avoid overflow when n == MIN_VALUE
}
double ans = 1, tmp = x;
while (n != 0) {
if (n % 2 == 1) {
ans *= tmp;
}
tmp *= tmp;
n /= 2;
}
if (isNegative) {
ans *= x;
}
return ans;
}
}