字符串转化后的个位数字之和【LC1945】
You are given a string s consisting of lowercase English letters, and an integer k.
First, 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). Then, transform the integer by replacing it with the sum of its digits. Repeat the transform operation k times in total.
For example, if s = "zbax" and k = 2, then the resulting integer would be 8 by the following operations:
- Convert: "zbax" ➝ "(26)(2)(1)(24)" ➝ "262124" ➝ 262124
- Transform #1: 262124 ➝ 2 + 6 + 2 + 1 + 2 + 4 ➝ 17
- Transform #2: 17 ➝ 1 + 7 ➝ 8
Return the resulting integer after performing the operations described above.
第三天啦 还没有烧
- 思路:由于k一定大于0,因此可以边遍历字符串,边求出第一次转化后的数位之和,然后使用for循环遍历继续求出第k次的数位之和
- 实现
class Solution { public int getLucky(String s, int k) { int res = 0; for (int i = 0; i < s.length(); i++){ res += getSumOfDigits(s.charAt(i) - 'a' + 1); } for (int i = 1; i < k; i++){ res = getSumOfDigits(res); } return res; } public int getSumOfDigits(int n){ int res = 0; while (n % 10 > 0 || n / 10 > 0){ res += n % 10; n /= 10; } return res; } }
。复杂度
- 时间复杂度:O ( n )
- 空间复杂度:O ( 1 )