Happy Number

medium Number Problems

Problem

Start with a number. Replace it with the sum of the squares of its digits. Repeat. If you reach 1, the number is happy. If you go around in a cycle without reaching 1, it is not happy. Read a positive integer and print true if it is happy, otherwise false. Example: 19 -> 82 -> 68 -> 100 -> 1.

Constraints

  • 1 <= n <= 10^9

Examples

Input

19

Output

true

Input

4

Output

false

Solutions

Best approachTime O(log n)Space O(log n)

We repeat the digit-square sum. A set remembers all numbers we have already seen. If we see a number again, the process repeats forever, so the number is not happy.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Check if a number is a happy number.
 * Input   : One integer.
 * Output  : true or false.
 * Approach: Replace the number by the sum of the squares of its digits again and again.
 * Time    : O(log n)
 * Space   : O(log n)
 * Java    : 8 or newer.
 */
import java.util.HashSet;
import java.util.Set;
import java.util.Scanner;

public class Main {
    // This method receives a number and returns true if the number is a happy number.
    static boolean isHappy(long number) {
        // Step 1: Only positive numbers are checked.
        if (number < 1) {
            return false;
        }

        // Step 2: Remember every number we have seen. If a number comes again, we are in a cycle.
        Set<Long> seen = new HashSet<>();

        // Step 3: Repeat until we reach 1 or see a number for the second time.
        while (number != 1 && !seen.contains(number)) {
            seen.add(number);

            // Step 4: Replace the number with the sum of the squares of its digits. Example: 19 -> 1 * 1 + 9 * 9 = 82.
            long sum = 0;
            long remaining = number;
            while (remaining > 0) {
                long digit = remaining % 10;
                sum = sum + digit * digit;
                remaining = remaining / 10;
            }
            number = sum;
        }

        // Step 5: The number is happy only if we stopped at 1.
        return number == 1;
    }

    public static void main(String[] args) {
        long number = new Scanner(System.in).nextLong();
        System.out.println(isHappy(number));
    }
}
Hints (2)
  1. What stops the process when the number is not happy?
  2. A set can remember numbers and tell if a number is new.