ISC Computer Practical 2015 Question 1

Given two positive numbers M and N, such that M is between 100 and 10000 and N is less than 100. Find the smallest integer that is greater than M and whose digits add up to N. For example, if M=100 and N=11, then the smallest integer greater than 100 whose digits add up to 11 is 119.

Write a program to accept the numbers M and N from the user and print the smallest required number whose sum of all its digits is equal to N. Also, print the total number of digits present in the required number. The program should check for the validity of the inputs and display an appropriate message for an invalid input.

Test your program with the sample data and some random data:

Example 1:

INPUT: M = 100
       N = 11
OUTPUT: The required number = 119
        The total number of digits = 3

Example 2

INPUT: M = 1500
       N = 25
OUTPUT: The required number = 1699
        The total number of digits = 4

Example 3

INPUT: M = 99
       N = 11
OUTPUT: INVALID INPUT

Example 4

INPUT: M = 112
       N = 130
OUTPUT: INVALID INPUT

Solution

import java.util.*;
class Q1{
    public static int getSumOfDigits( int n ){
        int sum=0;
        for( int temp=n; temp>0; temp/=10 ){
            sum+=temp%10;
        }
        return sum;
    }
    public static int getNumOfDigits( int n ){
        int count=0;
        for( int temp=n; temp>0; temp/=10 ){
            count++;
        }
        return count;
    }
    public static void main( String args[] ){
        int M, N, sum;
        Scanner sc = new Scanner( System.in );
        System.out.print("INPUT:\tM= ");
        M=sc.nextInt();
        System.out.print("\tN= ");
        N=sc.nextInt();
        if( M<100 || M>10000 || N<0 || N>=100){
            System.out.println("OUTPUT:\tINVALID INPUT");
        }else{
            do{
                sum = getSumOfDigits(M);
                if(sum==N ){
                    System.out.println("OUTPUT:\tThe required number="+(M));
                    System.out.println("OUTPUT:\tTotal number of digits="+getNumOfDigits(M));
                }
                M++;
                if(M==Integer.MAX_VALUE){
                    System.out.println("No solution exist");
                    break;
                }
            }while(sum!=N);
        }
    }
}

In the above program  was asked in the ISC Computer Practical 2015 please not that code of functions getNumberOfDigits() and getSumOfDigits() is nearly identical and the code could have been merged to obtain shorter code. But that would result in decreased efficiency because total number of digit is required only in those cases when the sum is equal to N and there is no point in calculating the same for failed cases.