Skip to content

1945. Sum of Digits of String After Convert 👍

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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;
    for (const char c : s) {
      const int val = c - 'a' + 1;
      // Do one transform to prevent integer overflow.
      sum += val < 10 ? val : (val % 10 + val / 10);
    }
    return sum;
  }

  int getDigitSum(int num) {
    int digitSum = 0;
    while (num > 0) {
      digitSum += num % 10;
      num /= 10;
    }
    return digitSum;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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(final String s) {
    int sum = 0;
    for (final char c : s.toCharArray()) {
      final 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;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def getLucky(self, s: str, k: int) -> int:
    ans = self._convert(s)
    for _ in range(k):
      ans = self._getDigitSum(ans)
    return ans

  def _convert(self, s: str) -> int:
    return int(''.join(str(string.ascii_lowercase.index(c) + 1) for c in s))

  def _getDigitSum(self, num: int) -> int:
    return sum(int(digit) for digit in str(num))