Recursive Digit Sum

题目:

For example:

  1. 数字9875的和将被计算为:和(9875)=9+8+7+5=29。总和(29)=11。总和(11)=2。
  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();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值