Skip to main content
Back to problems
#1945
Easy Algorithms

Sum of digits of string after convert

String Simulation
74.8% acceptance
Feb 25, 2026
1198
104
You are given a string s consisting of lowercase English letters, and an integer k. Your task is to convert the string into an integer by a special process, and then transform it by summing its digits repeatedly k times. More specifically, perform the following steps: Convert s 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). Transform the integer by replacing it with the sum of its digits. Repeat the transform operation (step 2) k times in total.

Solution

Rust
Time O(n²)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn get_lucky(s: String, k: i32) -> i32 {
    // Convert to digit string
    let mut num_str = String::new();
    for b in s.bytes() {
      num_str.push_str(&((b - b'a' + 1) as u32).to_string());
    }

    let mut val: i32 = num_str.bytes().map(|b| (b - b'0') as i32).sum();
    for _ in 1..k {
      let mut sum = 0;
      let mut v = val;
      while v > 0 {
        sum += v % 10;
        v /= 10;
      }
      val = sum;
    }
    val
  }
}