1945. Sum of Digits of String After Convert
UnknownView on LeetCode
Time: O(|s| + k * 10)
Space: O(|s|)
Problem Overview
Sum of Digits of String After Convert (Unknown) asks you to solve a structured algorithmic task. This is a common String / Simulation pattern in coding interviews. Convert letters to numbers, concatenate, then sum digits k times.
A full step-by-step explanation is being added. See the study guide for pattern-based practice.
Approach
Convert letters to numbers, concatenate, then sum digits k times.
Related patterns: String, Simulation
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;
}
}Was this solution helpful?