递归检查一个数字的所有数字是否都不相同

Recursively check if all digits of a number are different

本文关键字:数字 是否 递归 一个 检查      更新时间:2023-10-16

如何在c++中递归地检查整数的所有数字是否为不同的数字

void Check(int n)  
{
    if (n < 10)  
        return;  
    else  
    {
        bool eq = !(n % 10 == ((n / 10) % 10));  
        if (eq == true)  
        {  
            Check(n / 10);  
        }  
    }  
} 

你可以记住,哪些数字你已经看到了。例如,使用长度为10的bool数组。在第一次调用函数时,所有的项都是false。在每个递归调用中,将array[n%10]设置为true。如果它已经是true,那么你已经找到了一个重复的数字,否则没有。

如果只想使用递归,可以定义第二个递归函数:

bool checkIfDigitApearsInNumber(int n, int digit) {
    if (n == 0) {
       return false;
    } else {
       if (n % 10 == digit) {
          return true;
       } else {
          return checkIfDigitApearsInNumber(n/10, digit);
       }
    }
}

在函数Check中,您必须在n/10, n%10的每个步骤中调用该函数。