From 5a69916e0ff8c569b85090b6af97d9bddefff149 Mon Sep 17 00:00:00 2001 From: mengyuan Date: Fri, 22 Oct 2021 17:26:47 +0800 Subject: [PATCH] =?UTF-8?q?update:=200202.=E5=BF=AB=E4=B9=90=E6=95=B0=20js?= =?UTF-8?q?=E7=89=88=E6=9C=AC=20=E4=BD=BF=E7=94=A8Set()=EF=BC=8C=E6=B1=82?= =?UTF-8?q?=E5=92=8C=E7=94=A8reduce?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0202.快乐数.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/problems/0202.快乐数.md b/problems/0202.快乐数.md index 5704283d..d7a6b4e9 100644 --- a/problems/0202.快乐数.md +++ b/problems/0202.快乐数.md @@ -215,6 +215,23 @@ var isHappy = function(n) { } return n === 1; }; + +// 方法四:使用Set(),求和用reduce +var isHappy = function(n) { + let set = new Set(); + let totalCount; + while(totalCount !== 1) { + let arr = (''+(totalCount || n)).split(''); + totalCount = arr.reduce((total, num) => { + return total + num * num + }, 0) + if (set.has(totalCount)) { + return false; + } + set.add(totalCount); + } + return true; +}; ``` Swift: