LeetCode: Happy Number Solution
Use a Set to detect cycleApproach
Cycle here means a number is processed for the second time
Implementation
1var isHappy = function (n) {2 const set = new Set()34 while (true) {5 if (n === 1) break6 if (set.has(n)) return false7 set.add(n)89 let sum = 010 while (n) {11 const lastDigit = n % 1012 sum += lastDigit * lastDigit13 n = Math.floor(n / 10)14 }15 n = sum16 }17 return true18}
Implementation (shorter)
Don't want to waste time on social media?
1var isHappy = function (n) {2 const set = new Set()34 while (!set.has(n)) {5 set.add(n)6 n = String(n)7 .split("")8 .reduce((acc, digit) => acc + digit * digit, 0)9 }1011 return n === 112}
References
Similar problems
Sum of Digits of String After Convert
Minimum Addition to Make Integer Beautiful
Comments
Loading comments...
Tags
leetcode
hash table
math
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.
Next Post
LeetCode: Spiral Matrix
Writing recursive function is fun
Previous Post
LeetCode: Number of Islands
To be consistent, first find out how to make it easy