add: Pow(x, n)

This commit is contained in:
yi-ge 2020-05-11 13:15:10 +08:00
parent 02a4031bd6
commit 36b0434402
4 changed files with 40 additions and 6 deletions

View File

@ -11,6 +11,7 @@
"lrloseumgh",
"mincost",
"nums",
"powx",
"pwwkew",
"umghlrlose",
"xuan",

View File

@ -73,18 +73,18 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重
- [最后一个单词的长度](src/string/length-of-last-word.js)
- LeetCode 58. 最后一个单词的长度 https://leetcode-cn.com/problems/length-of-last-word/
- LintCode 422. 最后一个单词的长度 https://www.lintcode.com/problem/length-of-last-word/description
- LeetCode 58. 最后一个单词的长度 <https://leetcode-cn.com/problems/length-of-last-word/>
- LintCode 422. 最后一个单词的长度 <https://www.lintcode.com/problem/length-of-last-word/description>
- [整数转罗马数字](src/string/integer-to-roman.js)
- LeetCode 12. 整数转罗马数字 https://leetcode-cn.com/problems/integer-to-roman/
- LintCode 418. 整数转罗马数字 https://www.lintcode.com/problem/integer-to-roman/description
- LeetCode 12. 整数转罗马数字 <https://leetcode-cn.com/problems/integer-to-roman/>
- LintCode 418. 整数转罗马数字 <https://www.lintcode.com/problem/integer-to-roman/description>
- [罗马数字转整数](src/string/roman-to-integer.js)
- LeetCode 13. 罗马数字转整数 https://leetcode-cn.com/problems/roman-to-integer/
- LintCode 419. 罗马数字转整数 https://www.lintcode.com/problem/roman-to-integer/description
- LeetCode 13. 罗马数字转整数 <https://leetcode-cn.com/problems/roman-to-integer/>
- LintCode 419. 罗马数字转整数 <https://www.lintcode.com/problem/roman-to-integer/description>
## 数组
@ -319,6 +319,11 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重
- LeetCode 9. 回文数 <https://leetcode-cn.com/problems/palindrome-number/>
- LintCode 491. 回文数 <https://www.lintcode.com/problem/palindrome-number/>
- [Pow(x, n)](src/math/powx-n.js)
- LeetCode 50. Pow(x, n) <https://leetcode-cn.com/problems/powx-n/>
- LintCode 428. x的n次幂 <https://www.lintcode.com/problem/powx-n/>
## 堆
- [超级丑数](src/stack/super-ugly-number.js)【未完成】

21
src/math/powx-n.js Normal file
View File

@ -0,0 +1,21 @@
/**
* @param {number} x
* @param {number} n
* @return {number}
*/
export const myPow = function (x, n) { // 参考:快速幂 + 迭代 https://leetcode-cn.com/problems/powx-n/solution/powx-n-by-leetcode-solution/
let ans = 1.0 // 答案
if (n < 0) { // 如果 n 为负
n = -n // 将 n 变为正
x = 1.0 / x // 2^-2 = 1/(2^2) = 1/4 = 0.25
}
while (n > 0) {
if (n & 1) ans *= x // 如果n的二进制最后一位为1则计入贡献
x *= x // 将贡献不断平方
n >>>= 1 // 无符号右移一位,相当于 n = n / 2 | 0 ,去掉二进制的最后一位,相当于下一次判断倒数第二位
}
return ans.toFixed(5)
}

7
test/math/powx-n.test.js Normal file
View File

@ -0,0 +1,7 @@
import { myPow } from '../../src/math/powx-n'
test('Pow(x, n)', () => {
expect(myPow(2.00000, 10)).toBe('1024.00000')
expect(myPow(2.10000, 3)).toBe('9.26100')
expect(myPow(2.00000, -2)).toBe('0.25000')
})