Condense a Number (Digital Root) in Java

Beginner
⏱️ 9 min read
📚 Updated: May 2026
🎯 2 Code Examples
Digit manipulation

What you’ll learn

  • How repeated digit sums produce the digital root (the usual meaning of “condense” here).
  • An iterative Java program matching the reference flow, plus an O(1) base-10 formula for nonnegative inputs.
  • A live preview, modular arithmetic intuition (mod 9), and edge cases such as zero and large magnitudes.

Overview

Starting from a nonnegative integer, sum its decimal digits; if the result still has more than one digit, repeat. The final single digit is the digital root. Example: 9875 → 29 → 11 → 2.

Two programs

Iterative peel (reference style) and a closed form using % 9.

Live preview

Type a nonnegative integer and see the condensed digit.

Terminology

Clarifies digital root vs a single digit sum pass.

Prerequisites

Decimal representation, % 10 and / 10 digit peeling, and nested loops.

  • public static void main(String[] args), integer arithmetic, and printing with System.out.println.
  • Optional: modular arithmetic basics (n % 9) to understand the closed form.

Digital root vs digit sum

The digit sum of 9875 is 9+8+7+5 = 29. That is not yet one digit. The digital root keeps summing digits until the value lies in 0..9; here 29 → 11 → 2.

Many tutorials call this process “condensing” the number. It is not a different base; it is repeated reduction in base ten.

One pass digit sum
Repeat digital root
mod 9 closed form

Congruence mod 9

Because 10 ≡ 1 (mod 9), every decimal digit expansion satisfies n ≡ s(n) (mod 9) where s(n) is the digit sum. The same congruence holds after each condensation step, so the digital root is determined by n mod 9 with the usual 9 substitution for nonzero multiples of 9.

9875

9875 mod 9 = 2, matching the iterated sum chain ending at 2.

Intuition

18 Root 9
Chain
1+8 = 9
49 Root 4
Chain
13 → 4

Takeaway: each digit-sum step preserves the value modulo 9 (except the bookkeeping that maps a remainder of 0 to digital root 9 for positive n).

Live preview

Nonnegative integers in the JavaScript safe range. Uses the same repeated digit-sum rule as Example 1.

Negative values are not supported in this widget (match Example 1’s assumption).

Live result
Press “Condense” to see the digital root.

Algorithm (iterative)

Goal: reduce a nonnegative integer to a single decimal digit by repeated digit summation.

While the working value exceeds 9

Replace it by the sum of its decimal digits (peel with % 10 and / 10).

Stop

Return the last value (already in 0..9).

📜 Pseudocode

Pseudocode
function condense(n):  // n ≥ 0
    while n > 9:
        sum ← 0
        t ← n
        while t > 0:
            sum ← sum + (t mod 10)
            t ← floor(t / 10)
        n ← sum
    return n
1

Iterative condensation (reference flow)

Uses a working copy n so the outer loop condition is clear. Assumes nonnegative number; main keeps the original for printing.

java
public class Main {

    static int condenseNumber(int number) {
        int n = number;

        while (n > 9) {
            int sum = 0;
            int tmp = n;

            while (tmp > 0) {
                sum += tmp % 10;
                tmp /= 10;
            }

            n = sum;
        }

        return n;
    }

    public static void main(String[] args) {
        int number = 9875;
        int condensedNumber = condenseNumber(number);

        System.out.println("The condensed form of " + number + " is: " + condensedNumber);
    }
}

Explanation

The inner loop destroys tmp on each pass; n holds the next value to condense. The parameter number in main is unchanged because Java passes primitives by value.

while (n > 9)

Stopping rule. Single-digit results (including 0) exit immediately.

2

Closed form with long (mod 9)

Same mathematical answer for nonnegative inputs in a single step. Useful when n fits in long and you want O(1) time.

java
public class Main {

    // Precondition: n >= 0
    static int digitalRootNonnegative(long n) {
        if (n == 0) {
            return 0;
        }
        int r = (int)(n % 9);
        return (r == 0) ? 9 : r;
    }

    public static void main(String[] args) {
        long a = 9875L;
        long b = 999999999999999999L; // 18 nines

        System.out.println("dr(" + a + ") = " + digitalRootNonnegative(a) + " (closed form)");
        System.out.println("dr(" + b + ") = " + digitalRootNonnegative(b) + " (closed form)");
    }
}

Explanation

Eighteen nines sum to 162, whose digit sum is 9; the shortcut returns 9 immediately because n % 9 == 0 for nonzero n.

return (r == 0) ? 9 : r;

Map remainder 0 to root 9 for positive multiples of nine.

Optimization

mod 9 trick. Use the closed form when n is wide but fits your integer type; it avoids repeated scans of long digit strings.

Big integers. If n is stored as a string, either iterate digits once per round or reduce mod 9 in one pass over characters without building full long values.

Interview: define nonnegative policy, give 9875 trace, then cite the mod 9 formula.

❓ FAQ

It means the digital root: repeatedly replace the number by the sum of its decimal digits until a single digit remains. Example: 9875 → 9+8+7+5 = 29 → 2+9 = 11 → 1+1 = 2.
No. A single pass digit sum is not always one digit. Condensing (digital root) repeats until the value is in 0..9 (with 0 only for input 0 in the usual convention on this page).
For n > 0: let r = n % 9. The digital root is 9 if r == 0, else r. For n == 0, the digital root is 0. This follows because 10 ≡ 1 (mod 9), so n and its digit sum are congruent mod 9.
The process uses digit sums, but the mathematical name of the final single-digit result is the digital root. Using both terms is fine if you keep the iteration vs one-shot distinction clear.
The iterative code on this page assumes nonnegative integers (like the original). For interviews, define a policy: often digital root uses |n| for n ≠ 0, or reject negatives.
Iterative: each round costs O(d) in the number of digits d; the number of rounds is small for 32-bit ints. The closed form is O(1) time and O(1) space.

🔄 Input / output examples

Swap the literal in main or read with Scanner for interactive tests in Java.

InputDigital rootNotes
98752Reference walkthrough
00Both programs
99Already one digit
1891+8

Edge cases and pitfalls

The reference loop while (n > 9) never terminates for some negative conventions if you feed negatives in—keep inputs nonnegative or normalize first.

Zero

n = 0

The outer while is skipped; digital root 0. The closed form must special-case n == 0 before the 9 substitution.

Multiples of 9

n % 9 == 0, n > 0

The root is 9, not 0. Mixing that up breaks the closed form.

Types

Wide literals

Iterative summation on huge values needs wide intermediates; long plus % 9 is simpler when exact n fits.

Other bases

Beyond decimal

The mod 9 shortcut is specific to base ten. Other bases use different moduli.

⏱️ Time and space complexity

ApproachTimeExtra space
Iterative (32-bit int)Small constant number of digit passesO(1)
Iterative (asymptotic)O(D · R) digit work (digits D, rounds R; both tiny for interview int)O(1)
Closed formO(1)O(1)

For very large n as a string, one digit pass per round is O(L) per round in string length L.

Summary

  • Idea: repeated digit sum until one digit—the digital root.
  • Code: nested loops, or n==0 ? 0 : (n%9==0?9:n%9) for nonnegative n.
  • Watch-outs: clarify vs one-shot digit sum, 0, multiples of 9, negatives.
Did you know?

In base ten, the digital root (this page’s “condensed” value) is related to divisibility by 9: for n > 0, repeated digit sums eventually match 1 + (n - 1) % 9, with 9 instead of 0 when n is a nonzero multiple of 9.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful