add: 快乐数
This commit is contained in:
parent
de9ff35202
commit
ecab5b8850
@ -219,6 +219,11 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重
|
||||
- LeetCode 852. 山脉数组的峰顶索引 https://leetcode-cn.com/problems/peak-index-in-a-mountain-array/
|
||||
- LintCode 585. 山脉序列中的最大值 https://www.lintcode.com/problem/maximum-number-in-mountain-sequence/description
|
||||
|
||||
- [快乐数](src/array/happy-number.js)
|
||||
|
||||
- LeetCode 202. 快乐数 https://leetcode-cn.com/problems/happy-number/
|
||||
- LintCode 488. 快乐数 https://www.lintcode.com/problem/happy-number/description
|
||||
|
||||
## 栈
|
||||
|
||||
- [最大矩阵](src/stack/maximal-rectangle.js)
|
||||
|
14
src/array/happy-number.js
Normal file
14
src/array/happy-number.js
Normal file
@ -0,0 +1,14 @@
|
||||
/**
|
||||
* @param {number} n
|
||||
* @return {boolean}
|
||||
*/
|
||||
export const isHappy = function (n) {
|
||||
const set = new Set()
|
||||
|
||||
while (n !== 1 && !set.has(n)) {
|
||||
set.add(n)
|
||||
n = n.toString().split('').reduce((a, b) => a + b * b, 0)
|
||||
}
|
||||
|
||||
return n === 1
|
||||
}
|
6
test/array/happy-number.test.js
Normal file
6
test/array/happy-number.test.js
Normal file
@ -0,0 +1,6 @@
|
||||
import { isHappy } from '../../src/array/happy-number'
|
||||
|
||||
test('快乐数', () => {
|
||||
expect(isHappy(19)).toBe(true)
|
||||
expect(isHappy(5)).toBe(false)
|
||||
})
|
Loading…
Reference in New Issue
Block a user