Tuesday, 19 September 2017

Java Program to find largest digit in the given input and calculate the multiples of the largest digit with all individual digits to single digit

Question:

Program to find largest digit in the given input and calculate the multiples of the largest digit with all individual digits to single digit

Input: 123
Output: Result: 9

Program:

import java.io.*;

public class LetUsCodeinJava{
     public static void main(String[ ] args){
          String inpStr = "123";
          int res = 0, sum = 0;
          int maxDigit = Integer.parseInt(inpStr.charAt(0) + "");
          // to find max digit in the given string
          for(int i = 0; i < inpStr.length( ); i++){
               if(Integer.parseInt(inpStr.charAt(i) + "") > maxDigit){
                    maxDigit = Integer.parseInt(inpStr.charAt(i) + "");
               }
          }
          // multiples of the largest digit with all individual digits
          for(int i = 0; i < inpStr.length( ); i++){
               res += maxDigit * Integer.parseInt(inpStr.charAt(i) + "");
          }
          // sum of digits to single digit
          while(res > 0 || sum > 9){
               if(res == 0){
                     res = sum;
                     sum = 0;
               }
               sum += res % 10;
               res /= 10;
           }
           System.out.println("Result: "sum);
     }
}

Output:

Result: 9

Explanation:

We need to divide the program into 3 section
1. to find max digit in the given string.
2. multiples of the largest digit with all individual digits.
3. sum of resultant digits to single digit.

In the 1st section we will get the largest digit

maxDigit = 3:

In the 2nd section we need to multiply all the digits with maxDigit

so, 1 * 3 = 3, 2 * 3 = 6, 3 * 3 = 9

res = 3 + 6 + 9 = 18

In the 3rd section we are calculating the sum of digits into single digit

so, sum = 1 + 8 = 9

Hence, Result = 9.



0 comments:

Post a Comment