Skip to content

Commit 2996881

Browse files
solves sum of digits of string after convert
1 parent a74cda1 commit 2996881

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -467,7 +467,7 @@
467467
| 1933 | 🔒 [Check If String Is Decomposable Into Value EqualSubstrings](https://leetcode.com/problems/check-if-string-is-decomposable-into-value-equal-substring) | | |
468468
| 1935 | [Maximum Number of Words You Can Type](https://leetcode.com/problems/maximum-number-of-words-you-can-type) | [![Java](assets/java.png)](src/MaximumNumberOfWordsYouCanType.java) | |
469469
| 1941 | [Check if All Characters Have Equal Number of Occurrences](https://leetcode.com/problems/check-if-all-characters-have-equal-number-of-occurrences) | [![Java](assets/java.png)](src/CheckIfAllCharactersHaveEqualNumberOfOccurrences.java) | |
470-
| 1945 | [Sum of Digits of String After Convert](https://leetcode.com/problems/sum-of-digits-of-string-after-convert) | | |
470+
| 1945 | [Sum of Digits of String After Convert](https://leetcode.com/problems/sum-of-digits-of-string-after-convert) | [![Java](assets/java.png)](src/SumOfDigitsOfStringAfterConvert.java) | |
471471
| 1952 | [Three Divisors](https://leetcode.com/problems/three-divisors) | | |
472472
| 1957 | [Delete Characters to Make Fancy String](https://leetcode.com/problems/delete-characters-to-make-fancy-string) | | |
473473
| 1961 | [Check If String Is a Prefix of Array](https://leetcode.com/problems/check-if-string-is-a-prefix-of-array) | | |
+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// https://leetcode.com/problems/sum-of-digits-of-string-after-convert
2+
// T: O(|s|* k)
3+
// S: O(|s|)
4+
5+
public class SumOfDigitsOfStringAfterConvert {
6+
public int getLucky(String s, int k) {
7+
final String convertedString = convert(s);
8+
int num = sumOfDigits(convertedString);
9+
for (int i = 0 ; i < k - 1 ; i++) {
10+
num = sumOfDigits(num);
11+
}
12+
return num;
13+
}
14+
15+
private String convert(String s) {
16+
final StringBuilder result = new StringBuilder();
17+
for (int i = 0 ; i < s.length() ; i++) {
18+
result.append(s.charAt(i) - 'a' + 1);
19+
}
20+
return result.toString();
21+
}
22+
23+
private int sumOfDigits(int number) {
24+
int sum = 0;
25+
while (number > 0) {
26+
sum += number % 10;
27+
number /= 10;
28+
}
29+
return sum;
30+
}
31+
32+
private int sumOfDigits(String number) {
33+
int sum = 0;
34+
for (int i = 0 ; i < number.length() ; i++) {
35+
sum += number.charAt(i) - '0';
36+
}
37+
return sum;
38+
}
39+
}

0 commit comments

Comments
 (0)