-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path50.pow-x-n.js
85 lines (78 loc) · 1.1 KB
/
50.pow-x-n.js
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/*
* @lc app=leetcode.cn id=50 lang=javascript
*
* [50] Pow(x, n)
*
* https://leetcode-cn.com/problems/powx-n/description/
*
* algorithms
* Medium (37.81%)
* Likes: 869
* Dislikes: 0
* Total Accepted: 253.5K
* Total Submissions: 670.4K
* Testcase Example: '2.00000\n10'
*
* 实现 pow(x, n) ,即计算 x 的 n 次幂函数(即,x^n^ )。
*
*
*
* 示例 1:
*
*
* 输入:x = 2.00000, n = 10
* 输出:1024.00000
*
*
* 示例 2:
*
*
* 输入:x = 2.10000, n = 3
* 输出:9.26100
*
*
* 示例 3:
*
*
* 输入:x = 2.00000, n = -2
* 输出:0.25000
* 解释:2^-2 = 1/2^2 = 1/4 = 0.25
*
*
*
*
* 提示:
*
*
* -100.0 < x < 100.0
* -2^31 <= n <= 2^31-1
* -10^4 <= x^n <= 10^4
*
*
*/
// @lc code=start
/**
* @param {number} x
* @param {number} n
* @return {number}
*/
var myPow = function(x, n) {
if(n === 0 ) return 1
let k = n
let o = x
if(k<0){
k = -k
o = 1/o
}
let ans = 1
while(k>1){
if(k & 1){
k--
ans *= o
}
o *= o
k = k/2
}
return ans * o
}
// @lc code=end