From ecab5b88502f5d9cb116d9e399c105f20500d6e6 Mon Sep 17 00:00:00 2001 From: yi-ge Date: Thu, 30 Apr 2020 13:58:03 +0800 Subject: [PATCH] =?UTF-8?q?add:=20=E5=BF=AB=E4=B9=90=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 5 +++++ src/array/happy-number.js | 14 ++++++++++++++ test/array/happy-number.test.js | 6 ++++++ 3 files changed, 25 insertions(+) create mode 100644 src/array/happy-number.js create mode 100644 test/array/happy-number.test.js diff --git a/README.md b/README.md index 1c47296..05ec6db 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/src/array/happy-number.js b/src/array/happy-number.js new file mode 100644 index 0000000..2415b83 --- /dev/null +++ b/src/array/happy-number.js @@ -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 +} diff --git a/test/array/happy-number.test.js b/test/array/happy-number.test.js new file mode 100644 index 0000000..727ed57 --- /dev/null +++ b/test/array/happy-number.test.js @@ -0,0 +1,6 @@ +import { isHappy } from '../../src/array/happy-number' + +test('快乐数', () => { + expect(isHappy(19)).toBe(true) + expect(isHappy(5)).toBe(false) +})