6070. Calculate Digit Sum of a String

The description of problem:

You are given a string s consisting of digits and an integer k.

A round can be completed if the length of s is greater than k. In one round, do the following:

Divide s into consecutive groups of size k such that the first k characters are in the first group, the next k characters are in the second group, and so on. Note that the size of the last group can be smaller than k.
Replace each group of s with a string representing the sum of all its digits. For example, "346" is replaced with "13" because 3 + 4 + 6 = 13.
Merge consecutive groups together to form a new string. If the length of the string is greater than k, repeat from step 1.
Return s after all rounds have been completed.

Chinese version

给你一个由若干数字(0 - 9)组成的字符串 s ,和一个整数。

如果 s 的长度大于 k ,则可以执行一轮操作。在一轮操作中,需要完成以下工作:

将 s 拆分 成长度为 k 的若干 连续数字组 ,使得前 k 个字符都分在第一组,接下来的 k 个字符都分在第二组,依此类推。注意,最后一个数字组的长度可以小于 k 。
用表示每个数字组中所有数字之和的字符串来 替换 对应的数字组。例如,"346" 会替换为 "13" ,因为 3 + 4 + 6 = 13 。
合并 所有组以形成一个新字符串。如果新字符串的长度大于 k 则重复第一步。
返回在完成所有轮操作后的 s 。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/calculate-digit-sum-of-a-string

The intuition for above problem

recursion method to address this problem. It’s not hard to get that when you merge once the string with k step. The result is also a string. And I just use the same method to address this problem.

No other words. Just show my codes

#include <string>
#include <iostream>
#include <vector>
using namespace std;

class Solution {
public:
    string kdigitsSum(string s, int k){
        string res = "";
        int n = s.size();
        if(n < k) return s;
        int i = 0;
        while (i < n) {
            int j = i + k;
            if (j > n) j = n;
            int sum = 0;
            for (int l = i; l < j; l++) {
                sum += s[l] - '0';
            }
            res += to_string(sum);
            i = j;
        }
        return res;
    }
    string digitSum(string s, int k) {
        int n = s.size();
        if (n <= k) return s;
        string temp;
        temp = kdigitsSum(s, k);
        return digitSum(temp, k);
    }

};
int main() 
{
    // test the function of digitSum()
    Solution s;
    //input:s = "11111222223", k = 3
    //output:"135"
    string s1 = "11111222223";
    int k1 = 3;
    //output the results with some declarations
    cout << "The result of the function of digitSum() is: " << s.digitSum(s1, k1) << endl;
    return 0;
}

The corresponding results:

The result of the function of digitSum() is: 135
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值