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:

Last index of One
Basic Accuracy: 65.74% Submissions: 1347 Points: 1

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

Popular posts from this blog

problem 3: given two integers N and M. The problem is to find the number closest to N and divisible by M. If there are more than one such number, then output the one having maximum absolute value.

problem no 7:Given two numbers A and B, find Kth digit from right of AB.

Problem no 16: count the number of squares below N.