Leetcode 1945. Sum of Digits of String After Convert
You are given a string s
consisting of lowercase English letters and an integer k
. First, convert s
into an integer by replacing each letter with its position in the alphabet (i.e., convert ‘a’ to 1, ‘b’ to 2, …, ‘z’ to 26). Then, transform the resulting integer into a sum of its digits until you have performed the operation k
times. Return the resulting integer after performing the k
operations.
s
(1 <= s.length
<= 100).k
<= 10.Input: s = "iiii", k = 1
Output: 36
Explanation:
Input: s = "leetcode", k = 2
Output: 6
Explanation:
k
times.public class Solution {
public int getLucky(String s, int k) {
// Step 1: Convert each character to its corresponding number in string form
StringBuilder numStr = new StringBuilder();
for (char c : s.toCharArray()) {
int number = c - 'a' + 1;
numStr.append(number);
}
// Step 2: Convert the concatenated string of numbers into an integer and sum its digits
int result = sumOfDigits(numStr.toString());
// Step 3: Repeat the sum of digits operation k-1 more times
for (int i = 1; i < k; i++) {
result = sumOfDigits(Integer.toString(result));
}
return result;
}
private int sumOfDigits(String num) {
int sum = 0;
for (char c : num.toCharArray()) {
sum += c - '0';
}
return sum;
}
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.getLucky("iiii", 1)); // Output: 36
System.out.println(solution.getLucky("leetcode", 2)); // Output: 6
}
}
n
is the length of the string s
.Since m
(the number of digits) grows depending on the transformed integers, but given the constraints, this method operates efficiently.
n
is the length of the string s
, k
is the number of iterations, and m
is the number of digits in the number derived from s
.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?