Number Programs

Java Program to Check Spy Number

A Java program to check if a number is a Spy number.

Problem Description

Write a Java program to check if a number is a Spy number. A number is said to be a Spy number if the sum of all digits is equal to the product of all digits.

Code

SpyNumber.java
public class SpyNumber {
    public static void main(String[] args) {
        int num = 1124;
        int sum = 0, product = 1, temp = num;

        while (temp > 0) {
            int digit = temp % 10;
            sum += digit;
            product *= digit;
            temp /= 10;
        }

        if (sum == product)
            System.out.println(num + " is a Spy Number.");
        else
            System.out.println(num + " is not a Spy Number.");
    }
}

Output

1124 is a Spy Number.

Explanation

  1. Sum: 1 + 1 + 2 + 4 = 8.
  2. Product: 1 * 1 * 2 * 4 = 8.
  3. Check: 8 == 8.