1945. Sum of Digits of String After Convert
UnknownView on LeetCode
Time: O(|s| + k * 10)
Space: O(|s|)
Advertisement
Approach
Convert letters to numbers, concatenate, then sum digits k times.
Key Techniques
String
String problems range from simple character counting to complex pattern matching. Common approaches include two pointers, sliding window, prefix hashing, and the KMP algorithm. In C#, strings are immutable — use StringBuilder for efficient concatenation inside loops.
Simulation
Simulation problems require implementing the described process step by step. Focus on correctly handling edge cases and state transitions. Common in geometry, game problems, and string manipulation. Optimize only if the naive simulation exceeds the time limit.
1945.cs
C#
// Approach: Convert letters to numbers, concatenate, then sum digits k times.
// Time: O(|s| + k * 10) Space: O(|s|)
public class Solution
{
public int GetLucky(string s, int k)
{
int ans = Convert(s);
for (int i = 1; i < k; ++i)
ans = GetDigitSum(ans);
return ans;
}
private int Convert(string s)
{
int sum = 0;
foreach (char c in s)
{
int val = c - 'a' + 1;
// Do one transform to prevent integer overflow.
sum += val < 10 ? val : (val % 10 + val / 10);
}
return sum;
}
private int GetDigitSum(int num)
{
int digitSum = 0;
while (num > 0)
{
digitSum += num % 10;
num /= 10;
}
return digitSum;
}
}Advertisement
Was this solution helpful?