Happy Number

Square the digits of a number, add the squares, repeat, and decide whether the chain ever reaches 1.

Take a positive integer n and replace it with the sum of the squares of its digits, then do the same to the new number, again and again. If the number ever becomes 1, n is called a happy number. If it never does, n is not happy. Return true when n is happy and false otherwise.

Example 1
Input: n = 19
Output: true
Explanation: 1² + 9² = 82, 8² + 2² = 68, 6² + 8² = 100, 1² + 0² + 0² = 1.
Example 2
Input: n = 2
Output: false
Explanation: 2 → 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4, and from there the same numbers repeat without reaching 1.
Solution

The Idea

Write 19 on a sheet of paper. Square each digit, 1 and 81, add them, and write the total, 82, underneath. Do the same to 82: 64 + 4 makes 68. Then 36 + 64 makes 100, and 1 + 0 + 0 makes 1. From 1 nothing changes any more, because 1² is 1. So 19 is happy.

Now start from 2. The steps give 4, then 16, 37, 58, 89, 145, 42 and 20. The digits of 20 give 4 + 0 = 4, a number we have already written. Look at the two rows of boxes in the picture: the top row, labelled "n = 19", ends in the teal box 1, and the bottom row, labelled "n = 2", bends back from 20 to 4.

Top row: 19, 82, 68, 100, 1, with the added squares under each box, so 19 is happy. Bottom row: 2, 4, 16, 37, 58, 89, 145, 42, 20, and an arrow from 20 back to 4, a loop that never reaches 1.

Each number leads to one next number, so once 4 shows up a second time, the orange boxes from 4 to 20 repeat in the same order forever. Simply waiting for 1 would never end for 2. So the real question is: how do we know it is time to stop and answer false?

Could a chain avoid both 1 and a repeat by growing bigger and bigger? No. A digit squared is at most 81, so a number with four digits leads to at most 4 × 81 = 324, which is smaller than the number. Larger numbers shrink even faster, and from any number below 1000 the next one is at most 243 (9² + 9² + 9²).

So every chain soon stays among a limited set of small numbers, and it must hit a number it has seen before. That leaves two endings. Either the chain reaches 1 and stays there, or it falls into a loop without 1, like the orange boxes. The answer is true exactly when the repeat it settles into is 1.

Solution Approach

The code needs three things: the next number from the digits, a way to notice the repeat, and a rule for reading the answer. The repeat can be noticed by remembering every number seen, or with two markers that move at different speeds.

Getting the next number

How do we pick out the digits of 145 one at a time? The remainder 145 % 10 is the last digit, 5. Dividing with 145 / 10 drops that digit and leaves 14. Repeating both steps gives 4, then 1, and stops when the number is 0. Adding 25 + 16 + 1 gives 42, the box after 145 in the picture.

Can this sum get too big for an int? An int has at most 10 digits, and each digit adds at most 81, so the sum is at most 810. The largest int, 2,147,483,647, leads to just 260.

Remembering the numbers seen

What is the plainest way to notice a repeat? Put each number into a HashSet<Integer> as the chain goes. When the set already holds the number, the chain has started to repeat. This works, but for 2 it stores all nine numbers from 2 to 20, and the set grows with every chain.

Two markers at different speeds

Can we notice the loop without storing anything? Imagine two markers walking along the bottom row of the picture. The marker named slow moves one box at a time, and the marker named fast moves two boxes at a time. Once both are inside the loop of eight orange boxes, fast closes the gap to slow by one box on every move, so it must land on the same box.

For n = 2, slow starts on 2 and fast one box ahead, on 4. After seven moves both stand on 42. This way of finding a loop with a one-step and a two-step marker is known as Floyd's cycle detection, after the computer scientist Robert Floyd.

What if the chain reaches 1 instead? Then fast gets there first, and since 1 leads to 1, it stays there. For n = 19, fast is on 1 after two moves, while slow is still on 68.

Reading the answer

When should the walk stop? Either fast is on 1, or slow and fast are on the same number. In both cases n is happy exactly when fast is 1, so that single check gives the answer.

Java Solution

The method isHappy works in these steps:

  1. First, a helper method next(n) returns the sum of the squares of the digits of n. It starts a total, sum, at 0. Then a loop takes the last digit d with n % 10, adds d * d to sum, and drops the digit with n /= 10, until n is 0.
  2. In isHappy, the marker slow starts on n and the marker fast on next(n), one step ahead. If both started on n, they would count as meeting before either one had moved.
  3. A while loop runs as long as fast is not 1 and slow is not equal to fast. Each pass moves slow one step with next(slow) and fast two steps with next(next(fast)).
  4. After the loop, return fast == 1.

The main method runs both examples, the number 1 itself, 7, 1,111,111 and Integer.MAX_VALUE, and prints each number's next number and its answer.

Java
public class HappyNumber {

    public static boolean isHappy(int n) {
        int slow = n;
        int fast = next(n);
        while (fast != 1 && slow != fast) {
            slow = next(slow);                // one step
            fast = next(next(fast));          // two steps
        }
        return fast == 1;
    }

    // Sum of the squares of the digits of n.
    static int next(int n) {
        int sum = 0;
        while (n > 0) {
            int d = n % 10;                   // last digit
            sum += d * d;
            n /= 10;                          // drop the last digit
        }
        return sum;
    }

    public static void main(String[] args) {
        int[] tests = {19, 2, 1, 7, 1111111, Integer.MAX_VALUE};
        for (int n : tests) {
            System.out.println("n = " + n + ": next = " + next(n) + ", happy = " + isHappy(n));
        }
    }
}

Running it prints:

Output
n = 19: next = 82, happy = true
n = 2: next = 4, happy = false
n = 1: next = 1, happy = true
n = 7: next = 49, happy = true
n = 1111111: next = 7, happy = true
n = 2147483647: next = 260, happy = false

The line for 19 shows next = 82, the 1 + 81 under the box 82 in the picture, and happy = true. For 2 the next number is 4, the start of the orange loop, and the answer is false because the markers meet on 42, not on 1.

The line n = 1 needs no pass at all: fast starts on next(1), which is 1, so the loop test fails at once and the method returns true. Starting from 7, the chain runs 49, 97, 130, 10 and 1. The number 1,111,111 has seven digits 1, so its next number is 7, and it shares the answer of 7.

Look at the last line: the largest int, 2,147,483,647, gives 260, far from any overflow. Its chain continues 40, 16 and then joins the orange loop of Example 2, so it is not happy.

Complexity

The cost is one digit walk for n itself, then a short walk over small numbers.

  • Time: O(log n), because the first call of next visits each of the about log10 n digits of n, and every later number is at most 810. From such small numbers the markers meet or reach 1 within a fixed number of passes: at most 15 for every start below 1000, counted in a test run.
  • Space: O(1), because the method keeps only slow, fast, sum and d, while a HashSet of seen numbers would store the whole chain.

The same one-step and two-step markers find a loop of nodes in Linked List Cycle.