Problem: Write a program in Java to check whether the given number is a spy number or not.

A number whose sum of digits is equal to the product of its digits is called a spy number. For example, 1124.

Spy number Example

Steps to check spy number in Java:

  1. Input a number.
  2. Calculate the sum of its digits (sum).
  3. Calculate the product of its digits (product).
  4. Check, if sum==product. If so then the is a spy number otherwise not.
import java.util.Scanner;
 
public class Main
{
	public static void main(String[] args) {
	    Scanner in= new Scanner(System.in);
	    int digit, num; 
	    
		System.out.println("Enter a number");
		num = in.nextInt();
		
		int product = 1;
		int sum = 0;
		
		//Extract digit, add to sum and multiply to product
		while(num>0){
		    digit = num%10;
		    sum += digit;
		    product *= digit;
		    num=num/10;
		}
		
		if(sum == product)
		    System.out.println("Spy Number");
		else
		    System.out.println("Not a Spy Number");
	}
}

Output:

Enter a number
1124
Spy Number

Leave a Reply

fourteen − eight =