Spy number check – Computer Sir Ki Class

Login


Lost your password?

Don't have an account ?
Register (It's FREE) ×
  

Login
[lwa]



Exam Questions-ICSE2017-05A #JAVA#7256    siteicon   siteicon  

Problem Statement - Spy number check

Write a program to accept a number and check and display whether it is a spy number or not. (A number is spy if the sum of its digits equals the product of its digits.)
Example: consider the number 1124, Sum of the digits = 1 + 1 + 2 + 4 = 8
Product of the digits = 1 x 1 x 2 x 4 = 8

Solution

TC++ #7256

Run Output

Enter number: 1124
Spy number

import java.util.Scanner;

 public class SpyNumber {
 public static void main(String[] args) {
 Scanner scanner = new Scanner(System.in);
 System.out.print("Enter number: ");
 int n = scanner.nextInt();

 int sumOfDigits = 0;
 int productOfDigits = 1;
 while (n > 0) {
 int remainder = n % 10;
 sumOfDigits = sumOfDigits + remainder;
 productOfDigits = productOfDigits * remainder;
 n = n / 10;
 }

 if (sumOfDigits == productOfDigits) {
 System.out.println("Spy number");
 } else {
 System.out.println("Not a spy number");
 }
 }
 }

Sample output 1

Enter number: 1124
Spy number

Sample output 2

Enter number: 34
Not a spy number

Common Errors

  • Some time learners initialise product also as 0 which makes the products go to 0 for each successive remainder multiplications.


Share

CSKC| Created: 15-Apr-2019 | Updated: 28-Nov-2019|ICSE2017









Back