class Spy
{
int num; // stores the number
// constructor (assumed already defined)
Spy(int nn)
{
num = nn;
}
// recursively returns the sum of the digits of i
int sumOfDigits(int i)
{
if (i == 0)
return 0;
else
return i % 10 + sumOfDigits(i / 10);
}
// recursively returns the product of the digits of i
int prodOfDigits(int i)
{
if (i == 0)
return 1;
else
return (i % 10) * prodOfDigits(i / 10);
}
// checks whether num is a Spy number and displays the result
void check()
{
int s = sumOfDigits(num);
int p = prodOfDigits(num);
if (s == p)
System.out.println(num + " is a Spy number.");
else
System.out.println(num + " is not a Spy number.");
}
public static void main(String args[])
{
Spy ob = new Spy(1124);
ob.check();
}
}
Explanation: sumOfDigits(i) and prodOfDigits(i) each recursively strip the last digit of i (i%10), combine it with the recursive result on the remaining digits (i/10), and stop at i==0 (base case 0 for the sum so the trailing digit isn't counted twice, base case 1 for the product so it doesn't zero out the result). check() compares the two and prints the appropriate message. Tested (run for real): 1124 (sum=8, product=8) was correctly reported as a Spy number, 123 (sum=6, product=6) and 9 (single digit, sum=product=9) were also correctly reported as Spy numbers, and 122 (sum=5, product=4) was correctly reported as not a Spy number.