Smallest Integer ISC Computer Science 2015 Practical

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
Total number of digits = 3

Example 2
INPUT:
M = 1500
N = 25
OUTPUT:
The required number = 1699
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

import java.util.Scanner;
class Find{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        System.out.print("M = ");
        int m = Integer.parseInt(in.nextLine());
        System.out.print("N = ");
        int n = Integer.parseInt(in.nextLine());
        if(m < 100 || m > 10000 || n > 99){
            System.out.println("INVALID INPUT");
            return;
        }
        int num = 0;
        int count = 0;
        int x = m + 1;
        while(true){
            int sum = sumOfDigits(x);
            if(sum == n){
                num = x;
                count = countDigits(x);
                break;
            }
            x++;
        }
        System.out.println("The required number = " + num);
        System.out.println("Total number of digits = " + count);
    }
    public static int sumOfDigits(int n){
        if(n < 10)
            return n;
        return n % 10 + sumOfDigits(n / 10);
    }
    public static int countDigits(int n){
        if(n < 10)
            return 1;
        return 1 + countDigits(n / 10);
    }
}

Comments

Popular posts from this blog

Encrypt Program ISC Specimen 2023 Theory

No Repeat Program ISC Computer Science 2022 Semester 2 Theory

Bank Inheritance Program ISC Specimen 2023 Theory