Sponsored
Sponsored
This approach involves converting each character to its corresponding position in the alphabet and forming a numeric string. We then sum the digits of this number 'k' times to get the resulting integer.
Time Complexity: O(N + kM), where N is the length of the string and M is the number of digits in the transformed number.
Space Complexity: O(M), as we store the transformed number as a string.
1public class Solution {
2
3 private static int digitSum(String num) {
4 int sum = 0;
5 for (char ch : num.toCharArray())
6 sum += ch - '0';
7 return sum;
8 }
9
10 public static int sumOfDigitsAfterConvert(String s, int k) {
11 StringBuilder num = new StringBuilder();
12 for (char c : s.toCharArray())
13 num.append(c - 'a' + 1);
14
15 String result = num.toString();
16 while (k-- > 0) {
17 int sum = digitSum(result);
18 result = String.valueOf(sum);
19 }
20
21 return Integer.parseInt(result);
22 }
23
24 public static void main(String[] args) {
25 System.out.println(sumOfDigitsAfterConvert("zbax", 2));
26 }
27}
The conversion from character position to string number is done using StringBuilder
. The integer's digit sum is calculated iteratively k
times and updated as a string.
This approach directly calculates the digit sum during the conversion of the string to a number by aggregating the sum of each digit representation, reducing the need for intermediate large integer string handling.
Time Complexity: O(N + k*logM), where M is the intermediate sum value.
Space Complexity: O(1).
1#include <string>
using namespace std;
int sumOfDigitsAfterConvert(string s, int k) {
int sum = 0;
for (char c : s) {
int val = c - 'a' + 1;
while (val) {
sum += val % 10;
val /= 10;
}
}
for (int i = 1; i < k; i++) {
int newSum = 0;
while (sum) {
newSum += sum % 10;
sum /= 10;
}
sum = newSum;
}
return sum;
}
int main() {
cout << sumOfDigitsAfterConvert("zbax", 2) << endl;
return 0;
}
The character value is directly converted and its digit sum is accumulated inline, reducing intermediate conversions. Repetitive sum calculations are efficient due to direct digit manipulation.