Skip to content

Commit 7868332

Browse files
committed
Add AddDigits task solution
Add Youtube link to CheckCapitalUsage video
1 parent 9464d8a commit 7868332

File tree

3 files changed

+84
-0
lines changed

3 files changed

+84
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,3 +175,4 @@ they contain enough code which describes implementation in a natural way.
175175
- [Длина последнего слова в строке (3 решения) (leetcode)](https://www.youtube.com/watch?v=Kev5TpsfKT4)
176176
- [Парсинг списка строк в структуру данных (Яндекс)](https://www.youtube.com/watch?v=RW1DcmbzbQ8)
177177
- [Перемещение нулей к концу массива (leetcode)](https://youtu.be/IV5EIDRYZ9U)
178+
- [Проверка правильности использования заглавных букв (2 решения) (leetcode)](https://youtu.be/v0EkBQbFQpk)
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package by.andd3dfx.numeric;
2+
3+
/**
4+
* <pre>
5+
* https://leetcode.com/problems/add-digits/description/
6+
*
7+
* Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.
8+
*
9+
* Example 1:
10+
*
11+
* Input: num = 38
12+
* Output: 2
13+
* Explanation: The process is
14+
* 38 --> 3 + 8 --> 11
15+
* 11 --> 1 + 1 --> 2
16+
* Since 2 has only one digit, return it.
17+
*
18+
* Example 2:
19+
*
20+
* Input: num = 0
21+
* Output: 0
22+
* </pre>
23+
*/
24+
public class AddDigits {
25+
26+
public static int addDigits(int num) {
27+
if (num < 10) {
28+
return num;
29+
}
30+
31+
var sum = 0;
32+
while (num > 0) {
33+
sum += num % 10;
34+
num /= 10;
35+
}
36+
37+
return addDigits(sum);
38+
}
39+
40+
/**
41+
* https://en.wikipedia.org/wiki/Digital_root
42+
*/
43+
public static int addDigits_usingDigitalRoot(int num) {
44+
if (num == 0) {
45+
return 0;
46+
}
47+
48+
var remainder = num % 9;
49+
if (remainder == 0) {
50+
return 9;
51+
}
52+
53+
return remainder;
54+
}
55+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package by.andd3dfx.numeric;
2+
3+
import org.junit.Test;
4+
5+
import java.util.function.Function;
6+
7+
import static org.assertj.core.api.Assertions.assertThat;
8+
9+
public class AddDigitsTest {
10+
11+
@Test
12+
public void testAddDigits() {
13+
makeTestsNCheckAssertions(AddDigits::addDigits);
14+
}
15+
16+
@Test
17+
public void testAddDigits_usingDigitalRoot() {
18+
makeTestsNCheckAssertions(AddDigits::addDigits_usingDigitalRoot);
19+
}
20+
21+
private static void makeTestsNCheckAssertions(Function<Integer, Integer> func) {
22+
for (int i = 0; i <= 9; i++) {
23+
assertThat(func.apply(i)).isEqualTo(i);
24+
}
25+
assertThat(func.apply(15)).isEqualTo(6);
26+
assertThat(func.apply(38)).isEqualTo(2);
27+
}
28+
}

0 commit comments

Comments
 (0)