Easy Digit Problems Java

Happy Number in Java

Check whether a number is a happy number.

  • TimeO(log n) for the first step, then a small fixed amount of work
  • SpaceO(1) in practice, because the set stays small
  • Hints3
  • Read2 min
Quick answer

A happy number reaches 1 when you keep replacing it with the sum of the squares of its digits. For example, 19 goes to 82, 68, 100 and then 1. Numbers that are not happy never reach 1. They end up in an endless loop that always contains 4.

DigitsHashSetCycle detection
1

Problem statement

Write a program to check a happy number in Java. Take a positive number, add the squares of its digits, and repeat with the result. If you reach 1, it is happy. If the values start to repeat without reaching 1, it is not.

Input

An integer n.

Output

true if n is happy, otherwise false.

Examples

Example 1
Inputn = 19
Outputtrue

1 + 81 = 82, 64 + 4 = 68, 36 + 64 = 100, 1 + 0 + 0 = 1.

Example 2
Inputn = 20
Outputfalse

20 goes to 4, 16, 37, 58, 89, 145, 42 and then 20 again.

Constraints

  • 1 <= n <= 2^31 - 1
2

Think before you code

Reveal the questions to ask yourself first
  • How do you get the digits of a number one at a time?
  • How will the program know it is going in circles?
  • What is the answer for 1?
3

Hints

Open one at a time — try again after each.
1 Hint 1
Write a helper that returns the sum of squared digits. Use n % 10 and n / 10.
2 Hint 2
Store each value in a HashSet. If a value comes back, stop with false.
3 Hint 3
Shortcut: every unhappy number reaches 4, so you can stop at 1 or 4.
4

Approach

Reveal the step-by-step approach
  1. If n is 0 or negative, return false.
  2. While n is not 1:
    • If n was seen before, return false.
    • Remember n, then replace it with the sum of its squared digits.
  3. Return true.

Splitting a number into digits is the same trick used to find the sum of the digits. The set is a HashSet, whose add returns false for a repeat.

5

Dry run

Walk through the example step by step

Happy number in Java example with 19:

n   | squared digits  | next n
----+-----------------+-------
19  | 1 + 81          | 82
82  | 64 + 4          | 68
68  | 36 + 64         | 100
100 | 1 + 0 + 0       | 1
1   | stop            | happy
6

Solution

Reveal the full Java solution
Solution.java
import java.util.HashSet;
import java.util.Set;

public class HappyNumber {
    static int sumOfSquares(int n) {
        int sum = 0;
        while (n > 0) {
            int digit = n % 10;
            sum += digit * digit;
            n /= 10;
        }
        return sum;
    }

    public static boolean isHappy(int n) {
        if (n <= 0) {
            return false;
        }
        Set<Integer> seen = new HashSet<>();
        while (n != 1) {
            if (!seen.add(n)) {
                return false; // value came back: endless loop
            }
            n = sumOfSquares(n);
        }
        return true;
    }

    public static void main(String[] args) {
        System.out.println(isHappy(19)); // true
        System.out.println(isHappy(20)); // false
        System.out.println(isHappy(1));  // true
    }
}

This is the happy number in Java using while loop. The set guarantees that the loop stops: an int has at most 10 digits, so after one step the value is at most 10 * 81 = 810. From then on it must reach 1 or repeat.

Happy number in Java using for loop

This version needs no set. It uses the known fact that every number that is not happy reaches 4.

static boolean isHappyFor(int n) {
    if (n <= 0) return false;
    for (; n != 1 && n != 4; ) {
        int sum = 0;
        for (int x = n; x > 0; x /= 10) {
            sum += (x % 10) * (x % 10);
        }
        n = sum;
    }
    return n == 1;
}

Happy number in Java using recursion

The same idea, using sumOfSquares from the main solution. The method calls itself with the next value until it meets 1 or 4.

static boolean isHappyRecursive(int n) {
    if (n == 1) return true;
    if (n <= 0 || n == 4) return false;
    return isHappyRecursive(sumOfSquares(n));
}

All three gave the same answer for every number from 1 to 99,999 when we ran them.

for (int i = 1; i <= 50; i++) {
    if (isHappy(i)) System.out.print(i + " ");
}
// 1 7 10 13 19 23 28 31 32 44 49

After this happy number in Java program, try the magic number, the digital root and more Java coding questions. For guided practice, see the Java full stack course.

TimeO(log n) for the first step, then a small fixed amount of work
SpaceO(1) in practice, because the set stays small
7

Review before the interview

Common mistakes

  • Looping until n is 1 with no repeat check. It never ends for numbers like 20.
  • Adding the digits instead of their squares.
  • Stopping with false at any single digit. 7 is a single digit and is happy.

Edge cases to test

  • 1 is happy.
  • 7 is happy: 49, 97, 130, 10, 1.
  • 0 and negative numbers are not happy.

Interview follow-ups

  • How would you detect the loop with slow and fast pointers and no set?
  • How would you print the first n happy numbers?
  • Why can the value never be more than 810 after one step for an int?

Keep practising

Practising for Java interviews?

CodeBegun's Java Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.

Chat with us