problem no 26: Given a string S consisting only '0's and '1's, find the last index of the '1' present in it.
QUESTION:
Given a string S consisting only '0's and '1's, find the last index of the '1' present in it.
Example 1:
Input:
S = 00001
Output:
4
Explanation:
Last index of 1 in given string is 4.
Example 2:
Input:
0
Output:
-1
Explanation:
Since, 1 is not present, so output is -1.
ANSWER:
int lastIndex(string s)
{
if(s.size()==1)
{
if(s[0]=='1')
{
return 0;
}
else
{
return -1;
}
}
else
{
int onefound=0;
for(int i=s.size()-1;i>=0;i--)
{
if(s[i]=='1')
{
onefound=1;
return i;
}
}
if(onefound==0)
{
return -1;
}
}
}
Comments
Post a Comment