RitinMalhotra

ISC Practical 2015 - Question 3.

Oct 29th, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.36 KB | None | 0 0
  1. /**
  2. * The program inputs two integers 'm' and 'n' and prints the smallest integer greater than 'm' whose sum of digits is equal to 'n'.
  3. */
  4. import java.util.Scanner;
  5. public class Prac_2015
  6. {
  7.     public static int findsum(int num)
  8.     {
  9.         int i,x;
  10.         String a=Integer.toString(num);
  11.         int sum=0;
  12.         for(i=0;i<a.length();i++)
  13.         {
  14.             x=Character.getNumericValue(a.charAt(i));
  15.             sum+=x;
  16.         }
  17.         return sum;
  18.     }
  19.     public static int digPresent(int num)
  20.     {
  21.         String a=Integer.toString(num);
  22.         int i; int ct=0;
  23.         for(i=0;i<a.length();i++)
  24.         {
  25.             ct++;
  26.         }
  27.         return ct;
  28.     }
  29.     public static void main(String args[])
  30.     {
  31.         Scanner sc=new Scanner(System.in);
  32.         int m,n;  //ATQ- m is between 100 and 10000 and n is less than 100.
  33.         System.out.println("Please enter the greater number. It must be between 100 and 10000.");
  34.         m=sc.nextInt();
  35.         System.out.println("Please enter the smaller number. It must be a positive number lesser than 100.");
  36.         n=sc.nextInt();
  37.         if(m<100 || m>10000 || n<1 || n>99)
  38.         {
  39.             System.out.println("Invalid input. Please try again.");
  40.         }
  41.         else
  42.         {
  43.         int i; int sum=0,totaldig;
  44.         i=m+1;
  45.         while(i>m)
  46.         {
  47.             sum=findsum(i);
  48.             if(sum==n)
  49.             {
  50.                 break;
  51.             }
  52.             i++;
  53.         }
  54.                 totaldig=digPresent(i);
  55.                 System.out.println("The required number = "+i);
  56.                 System.out.println("Total number of digits = "+totaldig);
  57.         }
  58.         sc.close();
  59.     }
  60. }
Add Comment
Please, Sign In to add comment