Search code examples
c++algorithmduplicatesunique

Detecting repeating digits in a number


I am trying to build a method that would take an integer as input. Then split that integer into single digits and then store them inside a vector. I then use sort() to sort the vector so I can detect any repeating elements within the vector. Upon the first repeat, I want to return True, if no repeat, I want to return False.

#include <iostream>
#include <vector>
bool RepeatDigit(int number){
vector<int> temp;
while (number > 0){
    int digit = number % 10;
    number /= 10; 
    temp.push_back(digit);
}
sort(temp.begin(),temp.end());
for (int i = 0; i < temp.size() - 1; i++){
    if (temp[i] == temp[i+1]){
        return true;
        break;
    } else { 
        return false;
        break;
    }
}
return(0);
}

But when I use this method in my other method to filter out repeating numbers in a if statement:

if (numerator % n == 0 && RepeatDigit(numerator) == false){
//Do Stuff
}

It does not seem to work properly and numbers with repeating digits still appear to be not filtered out. Can anyone tell me where the problem is? Or is there a more simple to preform this operation?


Solution

  • Delete your else branch - it causes your cycle to break on first iteration, so it only checks if the first digit in temp is duplicated.

    Moreover, instead of RepeatDigit(numerator) == false you could simply write !RepeatDigit(numerator)