汇能网 >油气>天然气>

LeetCode 2243. Calculate Digit Sum of a String 当前播报

2023-05-27 23:31:02 来源:哔哩哔哩

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

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

Divide sinto consecutive groups of size ksuch that the first kcharacters are in the first group, the next kcharacters 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 swith 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 safter all rounds have been completed.

Example 1:

Input: s = "11111222223", k = 3

Output: "135"

Explanation: 

- For the first round, we divide s into groups of size 3: "111", "112", "222", and "23".  

Then we calculate the digit sum of each group: 1 + 1 + 1 = 3, 1 + 1 + 2 = 4, 2 + 2 + 2 = 6, and 2 + 3 = 5.  

So, s becomes "3" + "4" + "6" + "5" = "3465" after the first round. 

- For the second round, we divide s into "346" and "5".  

Then we calculate the digit sum of each group: 3 + 4 + 6 = 13, 5 = 5.   

So, s becomes "13" + "5" = "135" after second round. Now, s.length <= k, so we return "135" as the answer.

Example 2:

Input: s = "00000000", k = 3

Output: "000"

Explanation: 

We divide s into "000", "000", and "00". 

Then we calculate the digit sum of each group: 

0 + 0 + 0 = 0, 0 + 0 + 0 = 0, and 0 + 0 = 0. s becomes "0" + "0" + "0" = "000", whose length is equal to k, so we return "000".

需要2个循环,一个是每次字符串的长度>k,另一个是每次去用一个stringbuilder去存储处理的到数据;

下面是代码:

Constraints:

1 <= s.length <= 100

2 <= k <= 100

sconsists of digits only.

Runtime: 1 ms, faster than 89.94% of Java online submissions for Calculate Digit Sum of a String.

Memory Usage: 40.7 MB, less than 73.27% of Java online submissions for Calculate Digit Sum of a String.

责任编辑:
相关新闻
回到首页 回到顶部

关于我们 | 联系方式 | 征稿启事 | 广告服务 | 百度地图 |

本网站由汇能网版权所有,未经授权禁止复制或建立镜像  粤ICP备2022077823号-2

信箱:317493128@qq.co m 媒体合作QQ:317493128

电子商务协会 360安全认证 网络报警平台 不良举报中心 中国文明网 无线互联网
1999-2020 www.huineng.042.net All Rights Reserved