题目:
For example:
- 数字9875的和将被计算为:和(9875)=9+8+7+5=29。总和(29)=11。总和(11)=2。
- (n='9875',k=4)数字p是通过连接字符串n k次来创建的,因此初始p=9875987598759875(字符串'9875'重复4次)。
Input:
n=9875
k=4
Output:
8
注意点:当字符串过长时,int类型sum可能会超出,所以要用long型
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
import java.lang.Integer;
class Result {
/*
* Complete the 'superDigit' function below.
*
* The function is expected to return an INTEGER.
* The function accepts following parameters:
* 1. STRING n
* 2. INTEGER k
*/
public static int superDigit(String n, int k){
// Write your code here
long sum = 0;
char ch;
for(int i = 0; i < n.length(); i++){
ch = n.charAt(i);
if(ch < '0' || ch > '9'){
continue;
}
sum += Integer.parseInt(Character.toString(ch), 10);
}
sum *= k;
String str = Long.toString(sum);
while(str.length() > 1){
sum = 0;
for(int i = 0; i < str.length(); i++){
ch = str.charAt(i);
sum += Integer.parseInt(Character.toString(ch), 10);
}
str = Long.toString(sum);
}
return (int)sum;
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
String[] firstMultipleInput = bufferedReader.readLine().replaceAll("\\s+$", "").split(" ");
String n = firstMultipleInput[0];
int k = Integer.parseInt(firstMultipleInput[1]);
int result = Result.superDigit(n, k);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedReader.close();
bufferedWriter.close();
}
}