Write a program in Java to check whether a given number is Spy number or not.
A Spy number is a number whose sum of digits is equal to the product of its digits, Example – 1124.
So to check spy number in Java we need to follow the following steps.
- Input a number.
- Calculate the sum of its digits (
sum
). - Calculate the product of the same input number (
product
). - If
sum == product
then its a Spy number else not.
Let’s implement the same in Java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | 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
1 2 3 | Enter a number 1124 Spy Number |
If you have any doubts or suggestion then comment below.