gives repeated digits in an integer but only in one condition :
only if the repeated digit is the result of n%10 where n is the integer the user writes. If the repeated digit is not the result of n%10 , then the compiler gives a wrong result.
so the question is : how to make this code gives the repeated digit in an integer (regardless the fact that the repeated digit is the result of n%10 or not and especially with making the minimum of changes on the code)????????? ?????
#include <cstdlib>
#include <cstdio> // iostream is not guaranteed to have printf and scanf
#define TRUE 1
#define FALSE 0
usingnamespace std;
typedefint Bool;
int main()
{
Bool digit_seen[10]= {0};
int digit;
longint n;
int x;
printf("Enter a number: ");
scanf("%ld", &n);
while(n > 0){
digit = n % 10;
if(digit_seen[digit])
{
printf("Repeated digit:%d\n" , digit); // Moved this line
break;
}
digit_seen[digit]= TRUE;
n /= 10; // Had to add this line to avoid single-numbers
}
return 0;
}
Why would it print repeated digit: 3? In the case of 1223, 3 is not the repeated digit, only 2 is.
Let me describe each line:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
scanf("%ld", &n); // read the number
while(n > 0){ // While we are not done analyzing the number
digit = n % 10; // Get the least significant digit
if(digit_seen[digit]) // Have we seen this digit before? If this is the first time, then it's a no
{
printf("Repeated digit:%d\n" , digit); // Print the digit only because it's not the first time we've seen it
break; // exit the loop
}
digit_seen[digit]= TRUE; // Well, we've seen this digit now, let's memorize that
// so if we see the digit again, we can exit
n /= 10; // Remove that least significant digit, shift everything to the right.
} // Try with the next digit