You are given a string s consisting of lowercase English letters, and an integer k.
First, converts into an integer by replacing each letter with its position in the alphabet (i.e., replace 'a' with 1, 'b' with 2, …, 'z' with 26). Then, transform the integer by replacing it with the sum of its digits. Repeat the transform operation ktimes in total.
For example, if s = "zbax" and k = 2, then the resulting integer would be 8 by the following operations:
Input: s ="iiii", k =1Output: 36Explanation: The operations are as follows:- Convert:"iiii"➝"(9)(9)(9)(9)"➝"9999"➝9999- Transform #1:9999➝9+9+9+9➝36Thus the resulting integer is36.
Example 2:
1
2
3
4
5
6
7
Input: s ="leetcode", k =2Output: 6Explanation: The operations are as follows:- Convert:"leetcode"➝"(12)(5)(5)(20)(3)(15)(4)(5)"➝"12552031545"➝12552031545- Transform #1:12552031545➝1+2+5+5+2+0+3+1+5+4+5➝33- Transform #2:33➝3+3➝6Thus the resulting integer is6.
publicclassSolution {
// Main method to perform the conversionpublicintgetLucky(String s, int k) {
// Step 1: Convert each character to its alphabet position StringBuilder numSb =new StringBuilder();
for (char ch : s.toCharArray()) {
int num = ch -'a'+ 1;
numSb.append(num);
}
// Step 2: Sum digits `k` times String currStr = numSb.toString();
for (int i = 0; i < k; i++) {
currStr = sumOfDigits(currStr);
if (currStr.length() == 1) {
break;
}
}
return Integer.parseInt(currStr);
}
// Helper method to sum the digits of a number represented as a stringprivate String sumOfDigits(String numStr) {
int sum = 0;
for (char digit : numStr.toCharArray()) {
sum += Character.getNumericValue(digit);
}
return Integer.toString(sum);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
classSolution:
defgetLucky(self, s: str, k: int) -> int:
defget_alphabet_position(char):
return ord(char) - ord("a") +1# Step 1: Convert each character to its alphabet position numeric_string ="".join(str(get_alphabet_position(char)) for char in s)
# Function to sum the digits of a number represented as a stringdefsum_of_digits(num_str):
return str(sum(int(digit) for digit in num_str))
# Step 2: Sum digits `k` timesfor _ in range(k):
numeric_string = sum_of_digits(numeric_string)
if len(numeric_string) ==1:
breakreturn int(numeric_string)
⏰ Time complexity: O(k*n), where k is the number of iterations to sum digits, and n is the length of the input string s.
StringBuilder numericString can have a length up to 2n (assuming each alphabet position is a 2-digit number like ‘10’ to ‘26’). Hence, space required is O(n).
During k iterations of summing the digits, the largest space consumption happens initially when the numeric string is largest (2n). After each summing step, the length of the string reduces.