# LeetCode: Happy Number Solution

Use a Set to detect cycle

## Approach

Cycle here means a number is processed for the second time

## Implementation

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}var isHappy = function (n) {2  const set = new Set()3
4  while (true) {5    if (n === 1) break6    if (set.has(n)) return false7    set.add(n)8
9    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()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 === 112}```

Original problem

## Similar problems

Ugly Number

Sum of Digits of String After Convert

Minimum Addition to Make Integer Beautiful

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

Search Posts