If user enters a string, i want to make a function to check if a repetition of a certain number of zeroes follows an equal number of ones. Example: 001101 (correct), 01(correct),001010 (incorrect). I've tried to store the string in 2 separate strings and compare the size but my 2nd while loop isn't stopping.
void check(string num) {
string st0 = "", st1 = "";
int n = num.length();
int k = 0;
while (k < n) {
int i = 0;
while (num[i] == num[i 1]) {
st0.push_back(num.back());
num.pop_back();
k ;
i ;
}
st0.push_back(num.back());
num.pop_back();
k ;
int j = 0;
while (num[j] == num[j 1]) {
st1.push_back(num.back());
num.pop_back();
k ;
j ;
}
st1.push_back(num.back());
num.pop_back();
k ;
if (st0.size() != st1.size()) {
cout << "incorrect \n";
}
st0.clear();
st1.clear();
}
}
CodePudding user response:
Here you are testing the elements from left to right and you're adding to st0
the last elements from num
string. For example:
"111010": after the first while num = "111"
and st0 = "010"
while (num[i] == num[i 1]) {
st0.push_back(num.back());
num.pop_back();
k ;
i ;
}
And to fix you should add the first element tested not the last.
while( num[i] == num[i 1] && i 1 < n ){
st0.push_back(num[i]);
i ;
}
st0.push_back(num[i]);
i ;
You did the same mistake here
while (num[j] == num[j 1]) {
st1.push_back(num.back());
num.pop_back();
k ;
j ;
}
Fix:
while( num[i] == num[i 1] && i 1 < n){
st1.push_back(num[i]); // same here
i ;
}
st1.push_back(num[i]);
i ;
I used the same i
here so that we continue looping the string from where we left off in the first while.
But there is a more optimized solution if you're interested:
void check(string num)
{
int cnt0 = 0 , cnt1 = 0;
int n = num.length();
int i=0;
bool test = true ;
while (i<n){
/* we can use two variables and increment them instead of strings and compare them cauz we are not using the elements we just need the size of them */
while( num[i] == num[i 1] && i 1 < n ){
cnt0 ;
i ;
}
cnt0 ;
i ;
while( num[i] == num[i 1] && i 1 < n) {
cnt1 ;
i ;
}
cnt1 ;
i ;
if ( cnt1 != cnt0 ){
test = false ;
break;
}
cnt1 = 0;
cnt0 = 0;
}
if( test ) {
cout << "correct \n" ;
}
else {
cout << "incorrect \n" ;
}
}
In the above algorithm, as you can see, you only need the length of the string st0
and st1
so you could just use 2 int variables and test the difference between the two, this way is more memory efficient as well as slightly faster run times.