'How to find specific numbers of repeating consecutive digits?
I am having trouble making this function evaluate if a a six digit integer has either a set of two repeated consecutive digits or four. All other sets of repeated consecutive digits should evaluate to false.
Examples of good input: 122345, 133335
Bad input: 123335, 666478
Here is my code:
bool hasDuplicate(int number){
int rem, num, dig;
do {
rem = number % 10;
num = number / 10;
dig = num % 10;
if (rem == dig) {
return true;
}
else {
return hasDuplicate(num);
}
} while (number > 0);
return false;
}
Solution 1:[1]
Consider converting the number to string and then just scanning the characters in the string from left to right.
bool hasDuplicate(int number) {
std::string s = std::to_string(number);
bool good = false;
bool bad = false;
int consecutive = 1;
// deliberately starting at s[1]
for (size_t i = 1; i < s.size(); i++) {
bool dupe = (s[i - 1] == s[i]);
if (dupe) {
consecutive++;
}
// last iteration or this char is not a duplicate of the previous one
if ((i + 1 == s.size()) || (!dupe)) {
bool good_sequence = (consecutive == 2) || (consecutive == 4);
good = good || good_sequence;
bool bad_sequence = (consecutive == 3) || (consecutive > 4);
bad = bad || bad_sequence;
}
if (!dupe) {
consecutive = 1;
}
}
return good && !bad;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | selbie |
