Define a class to accept a number. Check if the sum of the largest digit and the smallest digit is an even number or an odd number. Print appropriate messages. Sample Input: 6425 3748 Largest digit: 6 8 Smallest digit: 2 3 Sample Output: Sum is even Sum is odd
Topic: Extracting digits of a number
Answer
import java.util.Scanner;
class DigitSum { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.print("Enter a number : "); int n = sc.nextInt();
int num = n, d, large = 0, small = 9, sum;
while(num > 0) { d = num % 10; if(d > large) large = d; if(d < small) small = d; num = num / 10; }
sum = large + small;
System.out.println("Largest digit : " + large); System.out.println("Smallest digit : " + small);
if(sum % 2 == 0) System.out.println("Sum is even"); else System.out.println("Sum is odd"); } }
Digit-extraction is the workhorse technique of this paper. The loop is always the same three lines: d = num % 10; takes the last digit ... process d ... num = num / 10; removes the last digit (integer division) and it runs while num > 0.
The important detail is how the two trackers are initialised. Set large = 0 so that any digit beats it, and small = 9 so that any digit is smaller. Reversing these — or setting both to the first digit without care — is the usual source of wrong answers.
Note that num is a working copy of n. Because the loop destroys its value, keeping the original in n lets you print or reuse it afterwards. Examiners look for this.
Trace 6425: digits come out as 5, 2, 4, 6. large ends at 6, small at 2, sum 8, which is even. Trace 3748: digits 8, 4, 7, 3 give large 8, small 3, sum 11, which is odd. Both match the samples.
n int - the number entered by the user (kept unchanged) num int - working copy of n, reduced digit by digit d int - the digit currently extracted large int - largest digit found so far small int - smallest digit found so far sum int - sum of the largest and smallest digits sc Scanner - object used to read input from the keyboard