How to show the digits which were repeated in c? -
the question show digits repeated in c.
so wrote this:
#include<stdio.h> #include<stdbool.h> int main(void){ bool number[10] = { false }; int digit; long n; printf("enter number: "); scanf("%ld", &n); printf("repeated digit(s): "); while (n > 0) { digit = n % 10; if (number[digit] == true) { printf("%d ", digit); } number[digit] = true; n /= 10; } homecoming 0; } but show repeated digits 1 time again , 1 time again (ex. input: 55544 output: 455)
i revised it:
#include<stdio.h> int main(void){ int number[10] = { 0 }; int digit; long n; printf("enter number: "); scanf("%ld", &n); printf("repeated digit(s): "); while (n > 0) { digit = n % 10; if (number[digit] == 1) { printf("%d ", digit); number[digit] = 2; } else if (number[digit] == 2) break; else number[digit] = 1; n /= 10; } homecoming 0; } it works!
however, want know how if need utilize boolean (true false), or more efficient way?
to create first version work, you'll need maintain track of 2 things:
have seen digit? (to observe duplicates) have printed out? (to output duplicates once)so like:
bool seen[10] = { false }; bool output[10] = { false }; // [...] digit = ...; if (seen[digit]) { if (output[digit])) { // duplicate, printed } else { // need print , set output true } } else { // set seen true } (once you've got working, can simplify ifs. 1 needed if combine 2 tests.)
your sec version there, complex. need is:
add 1 counter digit every time see it print number if counter two.digit = ...; counter[digit]++; if (counter[digit] == 2) { // sec time see digit // print out } n = ...; side benefit count each digit @ end.
c
No comments:
Post a Comment