【每日一题Day57】LC1945字符串转化后的个位数字之和 | 模拟

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

字符串转化后的个位数字之和【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(n)O(n)
      • 空间复杂度:O(1)O(1)O(1)
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值