Skip to content

Commit 514bfc1

Browse files
solves sum of digits in base k
1 parent 57fbe43 commit 514bfc1

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -446,7 +446,7 @@
446446
| 1826 | 🔒 [Faulty Sensor](https://leetcode.com/problems/faulty-sensor) | | |
447447
| 1827 | [Minimum Operations to Make the Array Increasing](https://leetcode.com/problems/minimum-operations-to-make-the-array-increasing) | [![Java](assets/java.png)](src/MinimumOperationsToMakeTheArrayIncreasing.java) | |
448448
| 1832 | [Check if the Sentence Is Pangram](https://leetcode.com/problems/check-if-the-sentence-is-pangram) | [![Java](assets/java.png)](src/CheckIfSentenceIsPangram.java) | |
449-
| 1837 | [Sum of Digits in Base K](https://leetcode.com/problems/sum-of-digits-in-base-k) | | |
449+
| 1837 | [Sum of Digits in Base K](https://leetcode.com/problems/sum-of-digits-in-base-k) | [![Java](assets/java.png)](src/SumOfDigitsInBaseK.java) | |
450450
| 1844 | [Replace All Digits with Characters](https://leetcode.com/problems/replace-all-digits-with-characters) | | |
451451
| 1848 | [Minimum Distance to the Target Element](https://leetcode.com/problems/minimum-distance-to-the-target-element) | | |
452452
| 1854 | [Maximum Population Year](https://leetcode.com/problems/maximum-population-year) | | |

src/SumOfDigitsInBaseK.java

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
public class SumOfDigitsInBaseK {
2+
public int sumBase(int n, int k) {
3+
return sumOfDigits(toBaseK(n, k));
4+
}
5+
6+
private int sumOfDigits(StringBuilder number) {
7+
int sum = 0;
8+
for (int index = 0 ; index < number.length() ; index++) {
9+
sum += number.charAt(index) - '0';
10+
}
11+
return sum;
12+
}
13+
14+
private StringBuilder toBaseK(int n, int k) {
15+
if (n == 0) return new StringBuilder("0");
16+
final StringBuilder result = new StringBuilder();
17+
while (n > 0) {
18+
result.append(n % k);
19+
n /= k;
20+
}
21+
return result.reverse();
22+
}
23+
}

0 commit comments

Comments
 (0)