×

Java Program to Add Digits Until the Number Becomes a Single Digit Number

We will develop Java programme that increase a number's digit count in order to reduce it to one. The issue is also known as the digit root problem.

Example

Consider the case where we need to calculate the sum for the number 534636 so that it can be reduced to a single digit.

5+3+4+6+3+6 = 27

We'll also include numbers 2 and 7.

2 + 7 = 9

The result is 9, which is a single digit.

Brute Force Approach

  • The total number of digits is calculated.
  • the sum into a recursive call.
  • Return the number if it is less than 10.
  • Let's put the reasoning above into a Java application.

Java Program1 for single digit number

import java . util . * ;  
public class SingleDigitNumber1  
{   
static int digitSum ( int number  )  
{  
int sum1 = 0 ;  
while ( number > 0 || sum1 > 9 )  
{  
if ( number == 0 )   
{  
number = sum1 ;  // assigning sum1 to number
sum1 = 0 ;  // assigning 0 to sum1
}  


sum1 = sum1 + number % 10 ;  


number = number / 10 ;  
}  


return sum1 ;  
}  


public static void main ( String args [ ] )  
{  
int number = 534636 ;  
System . out . println ( " The sum of digits is : "+ digitSum ( number ) ) ;  
}  
}  

Output

Java Program to Add Digits Until the Number Becomes a Single Digit Number

The above-mentioned issue can also be resolved without the use of loops and recursion. This is how it's done:

This method starts by determining if the number can be divided by nine or not.Put the digits together if the number is divisible to see if the sum is 9-divisible or not. The integer is divisible by nine if it is; otherwise, it is not.

27 is an example where (2 + 7) = 9. The result of adding the numerals is 9. The total is, therefore, divisible by 9.

The digits of a number (n) that is divisible by nine should be added together until they equal one digit, which is always nine. For instance:

n = 3762

Number sum: 3 + 7 + 6 + 2 Equals 18.

A single digit number can be created by adding the number 18 further.

18 = 1 + 8 = 9

If a number has the form 9x, the answer is always 9. Whenever an integer has the form 9x+k

The shape of a number can be 9x or 9x + k. The response in the first scenario is always 9. The answer to the second example is always k, which is the remainder.

  • Return 0 if number is 0.
  • Find the number's remainder using 9. (number%9).
  • If the remaining is 0, give 9, else give the remainder.
if number == 0  
   return 0;  
if number % 9 == 0        
    digitSum(number) = 9  
else                 
    digitSum(number) = number % 9 




SingleDigitNumber2.java
import java . io . * ;  
public class SingleDigitNumber2   
{  
static int digitSum ( int number )  
{  
if (number == 0)  
return 0;  
return (number % 9 == 0) ? 9 : (number % 9);  
}     
public static void main (String s[])  
{  
int number = 534636;  
System.out.println("The sum of digits is: "+digitSum(number));  
}  
}  

Output

Java Program to Add Digits Until the Number Becomes a Single Digit Number

SingleDigitNumber3.java

import java.util.Scanner;
public class  SingleDigitNumber3{
   public static int sum_of_digits(int num) {
      int ld = 0;
      int sum1 = 0;
      while(num != 0) {
         ld = num % 10;
         sum1 = sum1 + ld;
         num = num / 10;
      }     
      return sum1;
  }
  public static int digitSum(int num) {
     int r = num;
     while(r / 10 != 0) {
   r = sum_of_digits(r);
     }
     return r;
  }


  public static void main(String[] args) {
      int num = 0;
      int d = 0;
      Scanner s =  new Scanner(System.in);      
      System.out.print("Enter an  number: ");
      num = s.nextInt();
      d = digitSum(num);
      System.out.println("The sum of digits until" +
         " single digit of the number "+num+
         " = "+d);
      s.close();
  }
}

Output

Java Program to Add Digits Until the Number Becomes a Single Digit Number

SingleDigitNumber4.java

import java.util.Scanner ;
public class SingleDigitNumber4 {
   public static int digitSum ( int num ) {
      if ( num == 0) return 0 ;
      else if ( num % 9 == 0 ) 
        return 9 ;
      else
        return num % 9 ;
   }
   public static void main ( String [ ] args ) {
      int num = 0 ;
      int d = 0 ;
      Scanner s =  new Scanner ( System . in ) ;
      System . out . print ( " Enter an  number : " ) ;
      num = s . nextInt ( ) ;
      d = digitSum ( num ) ;
      System . out . println("The sum of digits until" +" single digit of the number "+num+" = "+d);
      s . close ( ) ;
  }
}

Output:

Java Program to Add Digits Until the Number Becomes a Single Digit Number

Another simultaneous solution to the above problem is

public static int digitalSum ( int number )   
{  
return 1 + (number - 1) % 9 ;  
}  

Related Topics

Manachers Algorithm in Java

Here, we'll go over the four scenarios once more in an effort to approach them differently and use the same strategy. The values of (centerRightPosition - currentRightPosition) and LPS length at...

3 minutes read.

Java 9 Interface Private Method

Java 9 provides us the facility to include private methods inside the java interface. In java 8 and earlier versions, we are supposed to use only constant variables and abstract...

3 minutes read.

How to Create an Object in Java

How to Create an Object in Java An object can be defined as a run time entity that contains the blue printof the class. It means that all the member functions...

5 minutes read.

Java String toUpperCase() methods

Java String toUpperCase() method is used to convert all the characters of the String into upper case. Syntax public String toUpperCase() public String toUpperCase(Locale locale) Returns It returns upper case String. Java String toUpperCase() Example 1: public...

1 minute read.

Java gc()

Garbage collection Java language provides different ways to perform the task of memory management. In Java, objects are declared and assigned references. Once lifeof an object is completed it is dereferenced...

4 minutes read.

Java throws

Java throws: The Java throws keyword is used with the signature of the method to indicate that the method may raise an exception. The method that uses the Java throws...

3 minutes read.

How to check version of java in Linux

Java is one of the most famous and thoroughly utilized programming tongues from one side of the world to the other. On the off chance that you are a Java...

2 minutes read.

Java Future Example

Future is an interface in the Java language that is a part of  java.util.concurrent package. It serves as a symbol for the output of an asynchronous computation. The interface offers ways to determine whether a computation has finished,  wait for it to finish, and receive its result. Once the task or calculation is finished, it cannot be undone. A Future interface offers ways to determine whether the computation is finished, to wait for it to finish, and to receive the computation's results. When the computation...

3 minutes read.

Volatile keyword in Java

Multiple threads can change a variable's value by using the volatile keyword. Making classes thread-safe is another application for it. It indicates that using a method or an instance of...

3 minutes read.

Transaction Management in java

Definition: A database application is an application that is running against a relational database and executes one or more transactions. A transaction is an executing program that contains some database operations,...

4 minutes read.

Rotate matrix by 90 degrees in Java | Rotate matrix in Java clockwise and anti-clockwise

In this article, you will be acknowledged about what is a matrix along with an example. Most importantly you will be equipped knowledge on how to rotate the matrix by...

4 minutes read.

Java IO file not found exception

One of the exception classes offered by the java.io package is FileNotFoundException. An exception is raised when we attempt to access a file that isn't present in the system. It...

4 minutes read.

Java vs Dot Net

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

3 minutes read.

Get year from date in Java

The getYear() method of the Java date class returns a number calculated by deducting 1900 from the year that contains or starts with the instant in time represented by this...

4 minutes read.

Java 13 New Features

The Java SE Platform's JDK 13 version is an open-source reference implementation defined by the Java Community's JSR 388 Process. The necessary modifications made in Java 13 are listed below....

6 minutes read.

Java Networking

Networking Networking is a way of communicating the devices. It is made up of various technologies like computers, switches, routers that are interconnected and share data among themselves. The two common network protocols: 1. TCP/IP TCP stands for...

10 minutes read.

Java Map Example

In Java, the Map is an interface that is used mainly to denote key and value pairs. The central concept and theme of this mapping in the java collection framework...

4 minutes read.

Arithmetic Operations on String in Java

Introduction Arithmetic, Relational, Bitwise, and Logical operators are all available in Java. Simple mathematical calculations are performed using Java arithmetic operators. Basic Arithmetic operators are considered in Java to be Addition,...

4 minutes read.

Java vs Go

Java: Java is an object oriented programming language. It is also known as multi threaded language. It was designed by James gosling in the year 1995. We can also say that...

4 minutes read.

What is anagram in Java?

In this section will explain what an anagram is in Java and demonstrate how to determine whether or not a text is an anagram. In Java interviews, the anagram Java...

4 minutes read.