Skip to content

Commit 21024b3

Browse files
AddDigits : Accepted
1 parent 6b7fc0b commit 21024b3

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,7 @@ My accepted leetcode solutions to some of the common interview problems.
143143
- [Count Primes](problems/src/math/CountPrimes.java) (Easy)
144144
- [Rotate Function](problems/src/math/RotateFunction.java) (Medium)
145145
- [Water and Jug Problem](problems/src/math/WaterAndJugProblem.java) (Medium)
146+
- [Add Digits](problems/src/math/AddDigits.java) (Easy)
146147

147148
#### [Stack](problems/src/stack)
148149

problems/src/math/AddDigits.java

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package math;
2+
3+
/**
4+
* Created by gouthamvidyapradhan on 02/08/2017.
5+
* Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
6+
7+
For example:
8+
9+
Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
10+
11+
Follow up:
12+
Could you do it without any loop/recursion in O(1) runtime?
13+
14+
*/
15+
public class AddDigits {
16+
17+
public static void main(String[] args) throws Exception{
18+
System.out.println(new AddDigits().addDigits(38));
19+
}
20+
21+
public int addDigits(int num) {
22+
if(num == 0) return 0;
23+
return num % 9 == 0 ? 9 : num % 9;
24+
}
25+
26+
}

0 commit comments

Comments
 (0)