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
Topic: Checking for a Spy number
Answer
import java.util.Scanner;
class Spy { 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, sum = 0, prod = 1;
while(num > 0) { d = num % 10; sum = sum + d; prod = prod * d; num = num / 10; }
System.out.println("Sum of digits = " + sum); System.out.println("Product of digits = " + prod);
if(sum == prod) System.out.println(n + " is a Spy number"); else System.out.println(n + " is not a Spy number"); } }
The standard digit-extraction loop gathers both totals in a single pass.
The detail that decides the answer is the INITIALISATION of the two accumulators: sum starts at 0, because it is built by addition prod starts at 1, because it is built by multiplication Setting prod to 0 would leave the product at 0 for every number, and the program would report nearly everything as not a spy number. That single character is the whole marking point.
Keep the original in n, since the loop destroys num and n is needed for the final message.
Trace 1124: digits come out 4, 2, 1, 1. Sum = 8 and product = 8, so the two match and 1124 is a spy number, exactly as the question states.
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 sum int - running total of the digits (starts at 0) prod int - running product of the digits (starts at 1) sc Scanner - object used to read input