Wednesday 4 April 2018

Getting super digit of a number



Given an integer 'z' we can find it's super digit as follow:

If it is a single digit number then it itself is a super digit else the super digit is equal to the super digit of the digit-sum of 'z'.

Example:

1) Input: 5
SuperDigit = 5

2) Input: 1234

SuperDigit(1234) = SuperDigit(1+2+3+4)
                             = SuperDigit(10)
                             = SuperDigit(1+0)
                             = SuperDigit(1)
                             = 1

Input Format:
You are given two numbers n and k. You have to calculate the super digit of p. p is created when the number is concatenated k times. That is, if n= 756  and k=2, then p=756756.
That means you have to calculate super digit for 756756.

The first line contains two space-separated integers n and k.

Java Code:

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

   
    static int digitSum(String n, int k) {
       if(n.length()==1)
           return (Integer.valueOf(n));
        else{
            long sum=0;
            for(int i=0;i<n.length();i++)
            {
                sum=sum+(Long.parseLong(String.valueOf(n.charAt(i))));
               
            }
         
           
            String num=  String.format ("%d", sum);
            return digitSum(num,k);
        }
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String n = in.next();
        int k = in.nextInt();
        long sum=0;
        for(int i=0;i<n.length();i++)
            {
                sum=sum+(Long.parseLong(String.valueOf(n.charAt(i))));
               
            }
        sum=sum*k;
   
        int result = digitSum(Long.toString(sum), k);
        System.out.println(result);
        in.close();
    }
}

Constraints:

1<= n < 10^100000
1<= k< 10^5