How to check if a number has at least one pair of duplicate digits next to each other in C

1 Answer

0 votes
#include <stdio.h>
#include <stdbool.h>

bool hasDuplicateDigits(int n) {
    int prevDigit = n % 10; // Last digit
    n /= 10; // Remove the last digit

    while (n != 0) {
        int currentDigit = n % 10;
        if (currentDigit == prevDigit) {
            return true; 
        }
        prevDigit = currentDigit;
        n /= 10;
    }

    return false;
}

int main() {
    int number = 1233879; 
    
    if (hasDuplicateDigits(number)) {
        printf("%d has at least one pair of duplicate digits", number);
    } else {
        printf("%d does not have duplicate digits", number);
    }

    return 0;
}

 
 
 
/*
run:
 
1233879 has at least one pair of duplicate digits
 
*/

 



answered Jan 31, 2024 by avibootz
...