📜  自我编号

📅  最后修改于: 2021-04-27 19:45:43             🧑  作者: Mango

如果数字N不能写为M +对于任何M的M的数字总和,则称为N。
前几个Self编号是:

检查N是否是一个Self编号

给定整数N ,任务是查找此数字是否为“自身”数字。
例子:

方法:想法是从1迭代到N,对于每个数字,请检查其值的总和与数字的总和是否等于N。如果是,则该号码不是自己的号码。否则,该数字是一个自己的数字。
例如:

下面是上述方法的实现:

C++
// C++ implementation to check if the
// number is a self number or not
 
#include 
using namespace std;
 
// Function to find the sum of
// digits of a number N
int getSum(int n)
{
    int sum = 0;
    while (n != 0) {
        sum = sum + n % 10;
        n = n / 10;
    }
    return sum;
}
 
// Function to check for Self number
bool isSelfNum(int n)
{
    for (int m = 1; m <= n; m++) {
        if (m + getSum(m) == n)
            return false;
    }
    return true;
}
 
// Driver code
int main()
{
    int n = 20;
 
    if (isSelfNum(n)) {
        cout << "Yes";
    }
    else {
        cout << "No";
    }
    return 0;
}


Java
// Java implementation to check if the
// number is a self number or not
class GFG{
     
// Function to find the sum
// of digits of a number N
static int getSum(int n)
{
    int sum = 0;
    while (n != 0)
    {
        sum = sum + n % 10;
        n = n / 10;
    }
    return sum;
}
 
// Function to check for Self number
static boolean isSelfNum(int n)
{
    for(int m = 1; m <= n; m++)
    {
       if (m + getSum(m) == n)
           return false;
    }
    return true;
}
 
// Driver code
public static void main(String[] args)
{
    int n = 20;
 
    if (isSelfNum(n))
    {
        System.out.println("Yes");
    }
    else
    {
        System.out.println("No");
    }
}
}
 
// This code is contributed by Ritik Bansal


Python3
# Python3 implementation to check if the
# number is a self number or not
 
# Function to find the sum of
# digits of a number N
def getSum(n):
 
    sum1 = 0;
    while (n != 0):
        sum1 = sum1 + n % 10;
        n = n // 10;
     
    return sum1;
 
# Function to check for Self number
def isSelfNum(n):
 
    for m in range(1, n + 1):
        if (m + getSum(m) == n):
            return False;
     
    return True;
 
# Driver code
n = 20;
 
if (isSelfNum(n)):
    print("Yes");
 
else:
    print("No");
 
# This code is contributed by Code_Mech


C#
// C# implementation to check if the
// number is a self number or not
using System;
class GFG{
     
// Function to find the sum
// of digits of a number N
static int getSum(int n)
{
    int sum = 0;
    while (n != 0)
    {
        sum = sum + n % 10;
        n = n / 10;
    }
    return sum;
}
 
// Function to check for Self number
static bool isSelfNum(int n)
{
    for(int m = 1; m <= n; m++)
    {
       if (m + getSum(m) == n)
           return false;
    }
    return true;
}
 
// Driver code
public static void Main()
{
    int n = 20;
 
    if (isSelfNum(n))
    {
        Console.Write("Yes");
    }
    else
    {
        Console.Write("No");
    }
}
}
 
// This code is contributed by Code_Mech


Javascript


输出:
Yes

参考: https : //en.wikipedia.org/wiki/Self_number