Find the closest and smaller tidy number | C ++ program to find closest tidy number smaller than the given number ; check whether string violates tidy property ; if string violates tidy property , then decrease the value stored at that index by 1 and replace all the value stored right to that index by 9 ; Driver code ; num will store closest tidy number
#include <bits/stdc++.h> NEW_LINE using namespace std ; char * tidyNum ( char str [ ] , int len ) { for ( int i = len - 2 ; i >= 0 ; i -- ) { if ( str [ i ] > str [ i + 1 ] ) { ( char ) str [ i ] -- ; for ( int j = i + 1 ; j < len ; j ++ ) str [ j ] = '9' ; } } return str ; } int main ( ) { char str [ ] = "11333445538" ; int len = strlen ( str ) ; char * num = tidyNum ( str , len ) ; printf ( " % s STRNEWLINE " , num ) ; return 0 ; }