Lexicographic rank of a Binary String | C ++ 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 program
#include <iostream> NEW_LINE using namespace std ; void findRank ( string s ) { int N = s . size ( ) ; string bin ; for ( int i = 0 ; i < N ; i ++ ) { if ( s [ i ] == '0' ) bin += "0" ; else bin += "1" ; } long long X = 1ll << N ; long long res = 0 , val = 1 ; for ( int i = N - 1 ; i >= 0 ; i -- ) { if ( bin [ i ] == '1' ) res += ( val ) ; val *= 2ll ; } long long Y = res ; long ans = X + Y - 1 ; cout << ans ; } int main ( ) { string S = "001" ; findRank ( S ) ; return 0 ; }