-
Notifications
You must be signed in to change notification settings - Fork 0
/
AddDigits.java
42 lines (34 loc) · 1.01 KB
/
AddDigits.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/*
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
For example:
Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
*/
import java.io.*;
import java.util.*;
public class AddDigits {
public static int addDigits(int num) {
while(num >= 10){
int res = 0;
while(num >= 10){
res += num % 10;
num = num / 10;
}
num = res + num;
}
return num;
}
// https://en.wikipedia.org/wiki/Congruence_relation
public static int addDigits2(int num) {
return num == 0 ? 0 : (num % 9 == 0 ? 9 : num % 9);
}
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Enter a number: ");
int n = reader.nextInt();
int res = addDigits(n);
System.out.println("Digits added: " + res);
return;
}
}