Last index of One in java

Last index of One in java

Given a string S consisting only 0s and 1s, find the last index of the 1 present in it.

Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)

Input

  • The only line contains a string S.

Constraints

  • 1 <= |S| <= 10^6
  • S = {0,1}

Output

Print the last index of 1. If 1 is not present in the string, print -1.

Example

Sample Input

00001

Sample Output

4

Explanation

Last index of  1 in given string is 4.

Solution of Last index of One in java:–

import java.util.*;
import java.lang.*;
import java.io.*;

public class Main
{
	public static void main (String[] args) throws java.lang.Exception
	{
		//your code here
      Scanner sc = new Scanner (System.in);
      String str = sc.next();
      char s1[] = str.toCharArray();
      int index=0,temp=-1;
      for(int i=str.length()-1;i>=0;i--)
        {
          if(s1[i]=='1')
          {
             temp=i;
             break;
          }
        }
      
      System.out.println(temp);
      
	}
}

Add a Comment

Your email address will not be published. Required fields are marked *