Java Program to Condense a Number

Condense a Number

In the following example, we will condense a number (8654) into a single digit (5).

i.e., 8654 = 8 + 6 + 5 + 4
8654 = 23
8654 = 2 + 3
8654 = 5 (single digit)

Example

Java Compiler
public class myClass { static int myMethod(int a) { int copyNum = a; int remainder = 0; int result = 0; while(copyNum != 0) { remainder = copyNum % 10; result += remainder; copyNum = copyNum / 10; } return result; } public static void main(String[] args) { int num = 8654; int userValue = num; while(num > 9) num = myMethod(num); System.out.format("Single Digit of %d: %d\n", userValue, num); } }

Condense any Given Number

In the following example, we will condense any given number into a single digit.

Example

Java Compiler
import java.util.Scanner; public class myClass { static int myMethod(int a) { int copyNum = a; int remainder = 0; int result = 0; while(copyNum != 0) { remainder = copyNum % 10; result += remainder; copyNum = copyNum / 10; } return result; } public static void main(String[] args) { Scanner reader = new Scanner(System.in); System.out.print("Enter any Multi digit (int) number: "); int num = reader.nextInt(); int userValue = num; while(num > 9) num = myMethod(num); System.out.format("Single Digit of %d: %d\n", userValue, num); } }

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author