LeetCode: Happy Number Solution

Use a Set to detect cycle

Approach

Cycle here means a number is processed for the second time

Implementation

1var isHappy = function (n) {
2 const set = new Set()
3
4 while (true) {
5 if (n === 1) break
6 if (set.has(n)) return false
7 set.add(n)
8
9 let sum = 0
10 while (n) {
11 const lastDigit = n % 10
12 sum += lastDigit * lastDigit
13 n = Math.floor(n / 10)
14 }
15 n = sum
16 }
17 return true
18}

Implementation (shorter)

Don't want to waste time on social media?

1var isHappy = function (n) {
2 const set = new Set()
3
4 while (!set.has(n)) {
5 set.add(n)
6 n = String(n)
7 .split("")
8 .reduce((acc, digit) => acc + digit * digit, 0)
9 }
10
11 return n === 1
12}

References

Original problem

Similar problems

Linked List Cycle

Add Digits

Ugly Number

Sum of Digits of String After Convert

Minimum Addition to Make Integer Beautiful

Comments

Loading comments...

Tags

leetcode

hash table

math

Next Post

LeetCode: Spiral Matrix

Aug 25, 2022

Writing recursive function is fun

Previous Post

LeetCode: Number of Islands

Aug 23, 2022

To be consistent, first find out how to make it easy

HoningJS

Search Posts