add: 快乐数

This commit is contained in:
yi-ge 2020-04-30 13:58:03 +08:00
parent de9ff35202
commit ecab5b8850
3 changed files with 25 additions and 0 deletions

View File

@ -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
View 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
}

View File

@ -0,0 +1,6 @@
import { isHappy } from '../../src/array/happy-number'
test('快乐数', () => {
expect(isHappy(19)).toBe(true)
expect(isHappy(5)).toBe(false)
})