How to check if a number is composed of a pair of duplicate digits next to each other in C++

1 Answer

0 votes
#include <iostream>
#include <cmath>

bool hasDuplicateDigits(int n) {
    int total_digits = (int)floor(log10(n)) + 1;
     
    if (total_digits % 2 == 1) { // total digits not even
        return false;
    }
     
    while (n != 0) {
        int currentDigit = n % 10; 
        n /= 10; 
        int prevDigit = n % 10; 
        std::cout << prevDigit << " : " << currentDigit << "\n"; 
        if (currentDigit != prevDigit) {
            return false; 
        }
        n /= 10;
    }
 
    return true;
}
 
int main() {
    int number = 11338855; 
 
    if (hasDuplicateDigits(number)) {
        std::cout << "yes";
    } else {
        std::cout << "no";
    }
}
 
  
  
  
/*
run:
  
5 : 5
8 : 8
3 : 3
1 : 1
yes
  
*/
  



 



answered Jan 31, 2024 by avibootz
...