QuesAns Print Page – CSKC
Sign In

Search

siteicon
Q&A ICSE2014-05A #7425

Question:

A special two-digit number is such that when the sum of its digits is added to the product of its digits, the result is equal to the original twodigit number.

Example: Consider the number 59.
Sum of digits = 5 + 9 = 14
Product of its digits = 5 x 9 = 45
Sum of the sum of digits and product of digits= 14 + 45 = 59
Write a program to accept a two-digit number. Add the sum of its digits to the product of its digits. If the value is equal to the number input, output the message “Special 2-digit number” otherwise, output the message “Not a Special 2-digit number”.

Answer:

We create a Scanner object and accept the input number using nextInt() method. The input is stored in the variable ‘number’. It is given
in the question that the input will be a two digit number. We need to extract the two digits of the number into two variables ‘leftDigit’ and
‘rightDigit’. The left digit can be extracted by dividing the number by 10. (Note that ‘number’ is an int and the divisor 10 is an int. So, the
result will be an int and not a float i.e. we obtain only the quotient as the result). The right digit can be obtained by calculating the
remainder when ‘number’ is divided by 10.
Let us take an example input – number = 59.
Then, leftDigit = number / 10 = 59 / 10 = 5
rightDigit = number % 10 = 59 % 10 = 9
Once, we have the two numbers, calculating the sum and product of the digits is easy.

 

int sumOfDigits = rightDigit + leftDigit;
 int productOfDigits = rightDigit * leftDigit;

Next, we add the two variables above and store it in a new variable.

int sumOfProductAndSum = sumOfDigits + productOfDigits;

Finally, we use if else decision statements to check if the sum of product of digits and sum of digits is same as the input number and print
an appropriate message.

import java.util.Scanner;
 public class SpecialNumber {
 public static void main(String[] args) {
 Scanner scanner = new Scanner(System.in);
 System.out.print("Enter number: ");
 int number = scanner.nextInt();
 int rightDigit = number % 10;
 int leftDigit = number / 10;
 int sumOfDigits = rightDigit + leftDigit;
 int productOfDigits = rightDigit * leftDigit;
 int sumOfProductAndSum = sumOfDigits + productOfDigits;
 if (sumOfProductAndSum == number) {
 System.out.println("Special 2-digit number");
 } else {
 System.out.println("Not a Special 2-digit number");
 }
 }
 }