Arena / Problems /

202. Happy Number

Easy 0/10 Thrones Claimed
Prev Next

Problem Specification

LeetCode #202

Write an algorithm to determine if a number n is happy.

A happy number is a number defined by the following process:

  • Starting with any positive integer, replace the number by the sum of the squares of its digits.
  • Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
  • Those numbers for which this process ends in 1 are happy.

Return true if n is a happy number, and false if not.

Example 1
Input: n = 19
Output: true
Explanation:

12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

Example 2
Input: n = 2
Output: false
Constraints
  • 1 <= n <= 2^31 - 1
⚔️

Vacant Java Throne

No developer has claimed the Java throne for LeetCode #202 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.

Contenders & Community Submissions (1)

Peer solutions & challenges
#1 Alternative Java Solution by Anonymous Developer
0
Approach Intuition:
  1. It is more convenient to call isHappy(n) recursively. You only need to generate a new n as a parameter each time.
  2. If n has already appeared, it means that the loop has been entered, and return false. You can use Set to save the n that has appeared.
  3. Go is the iterative solution, other languages are the recursive solution.
class Solution {
    private HashSet<Integer> appearedNums = new HashSet<>();

    public boolean isHappy(int n) {
        appearedNums.add(n);

        var sum = 0;

        for (var digit : String.valueOf(n).toCharArray()) {
            sum += Math.pow(digit - '0', 2);
        }

        if (sum == 1) {
            return true;
        }

        if (appearedNums.contains(sum)) {
            return false;
        }

        return isHappy(sum);
    }
}
⚔️

Vacant Python Throne

No developer has claimed the Python throne for LeetCode #202 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.

Contenders & Community Submissions (1)

Peer solutions & challenges
#1 Alternative Python Solution by Anonymous Developer
0
Approach Intuition:
  1. It is more convenient to call isHappy(n) recursively. You only need to generate a new n as a parameter each time.
  2. If n has already appeared, it means that the loop has been entered, and return false. You can use Set to save the n that has appeared.
  3. Go is the iterative solution, other languages are the recursive solution.
class Solution:
    def __init__(self):
        self.appeared_nums = set()

    def isHappy(self, n: int) -> bool:
        self.appeared_nums.add(n)

        number = sum([int(digit) ** 2 for digit in str(n)])

        if number == 1:
            return True

        if number in self.appeared_nums:
            return False

        return self.isHappy(number)
⚔️

Vacant Javascript Throne

No developer has claimed the Javascript throne for LeetCode #202 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.

Contenders & Community Submissions (1)

Peer solutions & challenges
#1 Alternative Javascript Solution by Anonymous Developer
0
Approach Intuition:
  1. It is more convenient to call isHappy(n) recursively. You only need to generate a new n as a parameter each time.
  2. If n has already appeared, it means that the loop has been entered, and return false. You can use Set to save the n that has appeared.
  3. Go is the iterative solution, other languages are the recursive solution.
var isHappy = function (n, appearedNums) {
  appearedNums ||= new Set()
  let sum = 0

  for (const digit of n.toString()) {
    sum += Math.pow(Number(digit), 2)
  }

  if (sum == 1) {
    return true
  }

  if (appearedNums.has(sum)) {
    return false
  }

  appearedNums.add(sum)

  return isHappy(sum, appearedNums)
};
⚔️

Vacant C# Throne

No developer has claimed the C# throne for LeetCode #202 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.

Contenders & Community Submissions (1)

Peer solutions & challenges
#1 Alternative C# Solution by Anonymous Developer
0
Approach Intuition:
  1. It is more convenient to call isHappy(n) recursively. You only need to generate a new n as a parameter each time.
  2. If n has already appeared, it means that the loop has been entered, and return false. You can use Set to save the n that has appeared.
  3. Go is the iterative solution, other languages are the recursive solution.
public class Solution
{
    HashSet<int> appearedNums = new HashSet<int>();

    public bool IsHappy(int n)
    {
        appearedNums.Add(n);

        int sum = 0;

        foreach (char digit in n.ToString().ToCharArray())
            sum += (int)Math.Pow(digit - '0', 2);

        if (sum == 1)
            return true;

        if (appearedNums.Contains(sum))
            return false;

        return IsHappy(sum);
    }
}
⚔️

Vacant Go Throne

No developer has claimed the Go throne for LeetCode #202 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.

Contenders & Community Submissions (1)

Peer solutions & challenges
#1 Alternative Go Solution by Anonymous Developer
0
Approach Intuition:
  1. It is more convenient to call isHappy(n) recursively. You only need to generate a new n as a parameter each time.
  2. If n has already appeared, it means that the loop has been entered, and return false. You can use Set to save the n that has appeared.
  3. Go is the iterative solution, other languages are the recursive solution.
func isHappy(n int) bool {
    // Use map to track seen numbers
    seen := make(map[int]bool)

    for n != 1 && !seen[n] {
        seen[n] = true
        n = sumOfSquaredDigits(n)
    }

    return n == 1
}

func sumOfSquaredDigits(n int) int {
    sum := 0
    nStr := strconv.Itoa(n)
    for i := 0; i < len(nStr); i++ {
        digit := int(nStr[i] - '0')
        sum += digit * digit
    }
    return sum
}
⚔️

Vacant C++ Throne

No developer has claimed the C++ throne for LeetCode #202 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.

Contenders & Community Submissions (1)

Peer solutions & challenges
#1 Alternative C++ Solution by Anonymous Developer
0
Approach Intuition:
  1. It is more convenient to call isHappy(n) recursively. You only need to generate a new n as a parameter each time.
  2. If n has already appeared, it means that the loop has been entered, and return false. You can use Set to save the n that has appeared.
  3. Go is the iterative solution, other languages are the recursive solution.
class Solution {
public:
    bool isHappy(int n) {
        if (n == 1) {
            return true;
        }

        if (appeared_nums_.count(n)) {
            return false;
        }

        appeared_nums_.insert(n);

        return isHappy(getSum(n));
    }

private:
    unordered_set<int> appeared_nums_;

    int getSum(int n) {
        string n_str = to_string(n);
        int sum = 0;
        for (char digit : n_str) {
            sum += (digit - '0') * (digit - '0');
        }
        return sum;
    }
};
⚔️

Vacant Ruby Throne

No developer has claimed the Ruby throne for LeetCode #202 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.

Contenders & Community Submissions (1)

Peer solutions & challenges
#1 Alternative Ruby Solution by Anonymous Developer
0
Approach Intuition:
  1. It is more convenient to call isHappy(n) recursively. You only need to generate a new n as a parameter each time.
  2. If n has already appeared, it means that the loop has been entered, and return false. You can use Set to save the n that has appeared.
  3. Go is the iterative solution, other languages are the recursive solution.
def is_happy(n, appeared_nums = Set.new)
  return true if n == 1
  return false if appeared_nums.include?(n)

  appeared_nums.add(n)
  sum = n.to_s.chars.map { |digit| digit.to_i ** 2 }.sum

  is_happy(sum, appeared_nums)
end
⚔️

Vacant Rust Throne

No developer has claimed the Rust throne for LeetCode #202 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.

⚔️

Vacant Swift Throne

No developer has claimed the Swift throne for LeetCode #202 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.

⚔️

Vacant Kotlin Throne

No developer has claimed the Kotlin throne for LeetCode #202 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.