I am solving a problem where I need to return the last index of '1' in a given string. If not present then return -1. I wrote the following simple code, but for input string input "0" it fails. I tried to debug bu using GDB and I noticed that once loop statement of index()
function runs once then a garbage value is assigned to iteration variable i
.
#include <iostream>
#include <string>
using namespace std;
int index(string &str) {
int result = -1;
for(auto i = str.length() - 1; i >= 0; --i) {
if(str[i] == '1')
return i;
}
return result;
}
int main() {
int T;
cin >> T;
cin.ignore();
while(T--) {
string str;
cin >> str;
cout << index(str) << endl;
}
return 0;
}