C++ 如何使用递归检查数字是否有重复数字?
我需要知道一个数字是否有使用递归的重复数字,并返回“是”或“否”。我不允许使用循环或数组。这是我到现在为止对10个全局变量所做的,它是有效的,但我认为有更好的方法C++ 如何使用递归检查数字是否有重复数字?,c++,loops,pointers,recursion,C++,Loops,Pointers,Recursion,我需要知道一个数字是否有使用递归的重复数字,并返回“是”或“否”。我不允许使用循环或数组。这是我到现在为止对10个全局变量所做的,它是有效的,但我认为有更好的方法 #include <iostream> using namespace std; int counter0 = 0; int counter1 = 0; int counter2 = 0; int counter3 = 0; int counter4 = 0; int counter5 = 0; int counte
#include <iostream>
using namespace std;
int counter0 = 0;
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
int counter4 = 0;
int counter5 = 0;
int counter6 = 0;
int counter7 = 0;
int counter8 = 0;
int counter9 = 0;
bool check(int k) {
int p = k % 10;;
if (k < 10) {
return false;
} else {
if (p == 0) {
counter0++;
} else if (p == 1) {
counter1++;
} else if (p == 2) {
counter2++;
} else if (p == 3) {
counter3++;
} else if (p == 4) {
counter4++;
} else if (p == 5) {
counter5++;
} else if (p == 6) {
counter6++;
} else if (p == 7) {
counter7++;
} else if (p == 8) {
counter8++;
} else if (p == 9) {
counter9++;
}
if(counter1>1 || counter2>1 || counter3>1 || counter4>1 || counter5>1 || counter6>1 || counter7>1 || counter8>1 || counter9>1)
{
return true;
}
k=k/10;
check(k);
}
}
int main() {
//cout << "Hello, World!" << std::endl;
int n;
cin >> n;
cout << (check(n) ? "yes" : "no") << endl;
//cout << n/10;
return 0;
}
递归问题总是有一个基本情况和一个递归情况
基本情况很简单:首先,代码不正确。。。 如果输入n=11,它会显示“否”,但1会重复两次。您可以通过将if语句从ifk<10更改为ifk==0来修复它 你可以进入比特级别,但我看不出有多少有用。。。 总之,这是在没有阵列的情况下所能做的最好的
但是:如果您需要查找一个数字是否连续重复两次或两次以上,另一个答案是完美的您当前的代码与556或55或类似的数字不兼容,则不会给出答案。首先,确保您当前的代码工作正常
bool check(int k) {
if (k < 11)
return false;
int digit = k % 10;
int next = k / 10;
int digit2 = next % 10;
if (digit == digit2)
return true;
else
return check(next);
// Or in one expression:
// return (digit == digit2) || check(next);
}
#include <iostream>
using namespace std;
bool hasRepeatingDigit(int n, int mask)
{
// base case: if we have checked all the digits and didn't find any duplicates, return false
if (n == 0)
return false;
/*
p is the place of the last digit in n (n%10).
A digit can range from 0 to 9.
The place of 0 will be 1 << 0 which is 1.
The place of 1 will be 1 << 1 which is 2.
The place of 2 will be 1 << 2 which is 4.
...
...
The place of 9 will be 1 << 9 which is 512.
*/
int p = 1 << (n % 10);
// if place of p has already been marked then it's a duplicate
if (mask&p)
return true;
// otherwise scrap the last digit (n/10), mark place p and recurse on the remaining digits
return hasRepeatingDigit(n / 10, mask|p);
}
int main()
{
int n;
cin >> n;
cout << hasRepeatingDigit(n, 0) << endl;
}