Q1.) 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
Here is the solution to the first question of the 2015 ISC computer science practical:
Example 1
INPUT:
M =100
N = 11
OUTPUT:
The required number = 119
Total number of digits = 3
Here is the solution to the first question of the 2015 ISC computer science practical:
import java.io.*;
class sum{
int N=0;
int M=0; //variables for input
int count=0; //variable to count digits
int sum=0; //variable to find sum of digits
int flag=0; //will be used as a flag
int p = 0; //will store the answer
void main()throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the value of M and N:");
M = Integer.parseInt(br.readLine());
N = Integer.parseInt(br.readLine());
if(N<100>=100&&M<=10000){
while(flag==0){
p = M++;
int store = p;
while(p!=0){
int d = p%10;
sum = sum+d;
count++;
p = p/10;
}
if(sum==N){
flag = 1;
p = store;
}
else{
count = 0;
sum = 0;
}
}
System.out.println("The required number = "+p);
System.out.println("Total number of digits = "+count);
}
else{
System.out.println("Invalid Input");
}
}
}
0 comments:
Post a Comment