Lexicographic rank of a Binary String | Java program for the above approach ; Function to find the rank of a string ; Store the length of the string ; Stores its equivalent decimal value ; Traverse the string ; Store the number of strings of length less than N occurring before the given string ; Store the decimal equivalent number of string bin ; Store the rank in answer ; Print the answer ; Driver Code
import java . io . * ; import java . lang . * ; import java . util . * ; public class Main { static void findRank ( String s ) { int N = s . length ( ) ; StringBuilder sb = new StringBuilder ( " " ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( s . charAt ( i ) == '0' ) sb . append ( '0' ) ; else sb . append ( '1' ) ; } String bin = sb . toString ( ) ; long X = ( long ) Math . pow ( 2 , N ) ; long Y = Long . parseLong ( bin , 2 ) ; long ans = X + Y - 1 ; System . out . println ( ans ) ; } public static void main ( String [ ] args ) { String S = "001" ; findRank ( S ) ; } }