Java:以 k 为步长进行跳!然后再延伸k
class Solution {
public String digitSum(String s, int k) {
while (s.length() > k) {
int n = s.length();
StringBuilder sb = new StringBuilder(); // sb存!
for (int i = 0; i < n; i += k) {
int sum = 0;
for (int j = 0; j < k && i + j < n; j++) {
sum += s.charAt(i + j) - '0'; // s用于遍历!
}
sb.append(sum);
}
s = sb.toString();
}
return s;
}
}
Java:自己搓的代码…
class Solution {
public String digitSum(String s, int k) {
StringBuilder str = new StringBuilder(s);
int len = s.length();
while (len > k) {
String s1 = new String(str);
str.delete(0, str.length());
int a = 0;
for (int i = 0; i < len; ++i) {
// a += Integer.valueOf(s1.charAt(i)); // error 入参是String
a += s1.charAt(i) - '0';
if((i+1) % k == 0) {
str.append(String.valueOf(a));
a = 0;
}
}
if (len % k != 0) {
int b = 0;
for (int i = len - len % k; i < len; i++) {
b += s1.charAt(i) - '0';
}
str.append(String.valueOf(b));
}
len = str.length();
}
return String.valueOf(str);
}
}