diff --git a/.vscode/settings.json b/.vscode/settings.json index 2315d28..8167afe 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -11,6 +11,7 @@ "lrloseumgh", "mincost", "nums", + "powx", "pwwkew", "umghlrlose", "xuan", diff --git a/README.md b/README.md index e07f107..afed3c5 100644 --- a/README.md +++ b/README.md @@ -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. 最后一个单词的长度 + - LintCode 422. 最后一个单词的长度 - [整数转罗马数字](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. 整数转罗马数字 + - LintCode 418. 整数转罗马数字 - [罗马数字转整数](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. 罗马数字转整数 + - LintCode 419. 罗马数字转整数 ## 数组 @@ -319,6 +319,11 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重 - LeetCode 9. 回文数 - LintCode 491. 回文数 +- [Pow(x, n)](src/math/powx-n.js) + + - LeetCode 50. Pow(x, n) + - LintCode 428. x的n次幂 + ## 堆 - [超级丑数](src/stack/super-ugly-number.js)【未完成】 diff --git a/src/math/powx-n.js b/src/math/powx-n.js new file mode 100644 index 0000000..e34c610 --- /dev/null +++ b/src/math/powx-n.js @@ -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) +} diff --git a/test/math/powx-n.test.js b/test/math/powx-n.test.js new file mode 100644 index 0000000..3f79c7f --- /dev/null +++ b/test/math/powx-n.test.js @@ -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') +})