Largest number smaller than or equal to n and digits in non | C ++ program for efficient approach to find largest number having digits in non - decreasing order . ; Prints the largest number smaller than s and digits in non - decreasing order . ; array to store digits of number ; conversion of characters of string int number ; variable holds the value of index after which all digits are set 9 ; Checking the condition if the digit is less than its left digit ; If first digit is 0 no need to print it ; Driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void nondecdigits ( string s ) { long long m = s . size ( ) ; long long a [ m ] ; for ( long long i = 0 ; i < m ; i ++ ) a [ i ] = s [ i ] - '0' ; long long level = m - 1 ; for ( long long i = m - 1 ; i > 0 ; i -- ) { if ( a [ i ] < a [ i - 1 ] ) { a [ i - 1 ] -- ; level = i - 1 ; } } if ( a [ 0 ] != 0 ) { for ( long long i = 0 ; i <= level ; i ++ ) cout << a [ i ] ; for ( long long i = level + 1 ; i < m ; i ++ ) cout << "9" ; } else { for ( long long i = 1 ; i < level ; i ++ ) cout << a [ i ] ; for ( long long i = level + 1 ; i < m ; i ++ ) cout << "9" ; } } int main ( ) { string n = "200" ; nondecdigits ( n ) ; return 0 ; }