Computer Science

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 the 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 1Example 2
Input:
M = 100
N = 11
Input:
M = 1500
N = 25
Output:
The required number = 119
Total number of digits = 3
Output:
The required number = 1699
Total number of digits = 4
Example 3Example 4
Input:
M = 99
N = 11
Input:
M = 112
N = 130
Output:
Invalid Input
Output:
Invalid Input

Java

Java Iterative Stmts

ICSE 2016

11 Likes

Answer

import java.util.Scanner;

public class KboatNumber
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);

        System.out.print("Enter m: ");
        int m = in.nextInt();

        System.out.print("Enter n: ");
        int n = in.nextInt();

        if (m < 100 || m > 10000 || n < 1 || n >= 100) {
            System.out.println("Invalid Input");
            return;
        }

        int number = -1, count = 0;
        for (int i = m + 1; i < Integer.MAX_VALUE; i++) {
            int sum = 0;
            count = 0;
            int t = i;
            while (t != 0) {
                int d = t % 10;
                sum += d;
                t /= 10;
                count++;
            }

            if (sum == n) {
                number = i;
                break;
            }
        }

        if (number == -1) {
            System.out.println("Required number not found");
        }
        else {
            System.out.println("The required number = " + number);
            System.out.println("Total number of digits = " + count);
        }

    }
}

Output

Answered By

3 Likes


Related Questions