Leetcode-202 – Happy number


Happy number

Title Description: write an algorithm to judge whether a number n is a happy number.

“Happy number” is defined as:

  • For a positive integer, replace the number with the square sum of the numbers at each position each time.
  • Then repeat the process until the number becomes 1, or it may be an infinite loop, but it never becomes 1.
  • If it can be changed to 1, then this number is the happy number.
  • If n is a happy number, return true; If not, false is returned.

See leetcode’s official website for an example.

Source: leetcode
Link: https://leetcode-cn.com/probl…
The copyright belongs to Lingkou network. For commercial reprint, please contact the official authorization, and for non-commercial reprint, please indicate the source.

Solution 1: violent cracking

Since the sum of squares of the digits of the maximum value of int type is also a limited number, if a number is not a happy number, a cycle will occur after adding the sum of squares for many times, and it will terminate after the cycle, because the recalculation result is the same. The specific process is as follows. Use appearednums to record the numbers that have occurred:

  • Num starts from N and determines whether num appears in appearednums. If it does, a loop appears and returns false directly;
  • If it does not appear, calculate whether the sum of squares of each digit is 1. If it is 1, this number is a happy number; Otherwise, continue to assign sum to num and continue the next judgment.
import java.util.ArrayList;
import java.util.List;

public class LeetCode_202 {
    public static boolean isHappy(int n) {
        if (n == 1) {
            return true;
        List<Integer> appearedNums = new ArrayList<>();
        int num = n;
        while (!appearedNums.contains(num)) {
            int sum = 0;
            for (char c : String.valueOf(num).toCharArray()) {
                int cur = Integer.valueOf(String.valueOf(c));
                sum += cur * cur;
            if (sum == 1) {
                return true;
            } else {
                num = sum;
        return false;

    public static void main(String[] args) {

[daily message]Let it be, life will be much smoother, open-minded, and the world will be much softer.

Recommended Today

On the mutation mechanism of Clickhouse (with source code analysis)

Recently studied a bit of CH code.I found an interesting word, mutation.The word Google has the meaning of mutation, but more relevant articles translate this as “revision”. The previous article analyzed background_ pool_ Size parameter.This parameter is related to the background asynchronous worker pool merge.The asynchronous merge and mutation work in Clickhouse kernel is completed […]