Java Exercises: Accept a positive number and repeatedly add all its digits until the result has only one digit
Java Basic: Exercise-183 with Solution
Write a Java program to accept a positive number and repeatedly add all its digits until the result has only one digit.
Pictorial Presentation:
Sample Solution:
Java Code:
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Input a positive integer: ");
int n = in .nextInt();
if (n > 0)
System.out.println(add_digits_until_one(n));
}
public static int add_digits_until_one(int n) {
while (n > 9) {
int sum_digits = 0;
while (n != 0) {
sum_digits += n % 10;
n /= 10;
}
n = sum_digits;
}
return n;
}
}
Sample Output:
Input a positive integer: 25 7
Flowchart:
Java Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Java program to check if two binary trees are identical or not. Assume that two binary trees have the same structure and every identical position has the same value.
Next: Write a Java program to find the length of the longest consecutive sequence path of a given binary tree.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Java: Tips of the Day
How to sort an ArrayList?
Collections.sort(testList); Collections.reverse(testList);
That will do what you want. Remember to import Collections though!
Ref: https://bit.ly/32urdSe
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework