📌  相关文章
📜  Java程序来检查一个数字是否是间谍号码

📅  最后修改于: 2022-05-13 01:54:34.667000             🧑  作者: Mango

Java程序来检查一个数字是否是间谍号码

如果所有数字的总和等于所有数字的乘积,则称该数字为间谍数字。为了执行任务,我们需要反转需要 log(N) 时间的数字。

例子:

Input : 22
Output:  Given number is a SPY number.
Explanation: Sum of the number is 4 (2 + 2)
             Product of the number is as 4 (2 * 2) 
Input : 1241
Output:  Given number is not a SPY number.

方法:

  1. 计算输入数字的数字总和。
  2. 计算输入数字的数字的乘积。
  3. 如果数字总和等于数字的乘积,则该数字是间谍号码,否则不是。

下面是上述方法的实现:

Java
// Java Program to Check If a Number is Spy number or not
import java.io.*;
  
class GFG {
    public static void main(String[] args)
    {
        int product = 1, sum = 0, ld;
        int n = 22;
  
        // calculate sum and product of the number here.
        while (n > 0) {
            ld = n % 10;
            sum = sum + ld;
            product = product * ld;
            n = n / 10;
        }
  
        // compare the sum and product.
        if (sum == product)
            System.out.println(
                "Given number is spy number");
        else
            System.out.println(
                "Given number is not spy number");
    }
}


输出
Given number is spy number

复杂度:O(log(n))