字符串转化后的个位数字之和【LC1945】
You are given a string
sconsisting of lowercase English letters, and an integerk.First, convert
sinto an integer by replacing each letter with its position in the alphabet (i.e., replace'a'with1,'b'with2, …,'z'with26). Then, transform the integer by replacing it with the sum of its digits. Repeat the transform operationktimes in total.For example, if
s = "zbax"andk = 2, then the resulting integer would be8by 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 ➝ 8Return 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(n)O(n)
- 空间复杂度:O(1)O(1)O(1)
-

本文介绍了一种算法,该算法将输入的字符串中的每个字母转换为其在字母表中的位置对应的数字,然后对这些数字进行求和。重复此过程k次后返回最终的数字之和。
1万+

被折叠的 条评论
为什么被折叠?



