Find the closest and smaller tidy number
Last Updated :
11 Mar, 2024
Tidy Number are those number whose digits are arranged in non-decreasing order. Here, we are given a number and we have to find another number that is smaller but closest to the given number and also that number should be tidy, i.e., their digit should be in non-decreasing order.
Examples:
Input : 91234
Output : 89999
Tidy property is violated by appearing 1 after 9.
So, we will reduce 9 by 1 and the number right
to it will be replaced by 9. So, generated tidy
number is 89999.
Input : 45000
Output : 44999
The idea is to traverse from end. Whenever tidy property is violated, we reduce digit by one and make all subsequent digits 9.
C++
#include<bits/stdc++.h>
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\n" , num);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static String tidyNum(String str1,
int len)
{
char [] str = str1.toCharArray();
for ( int i = len - 2 ; i >= 0 ; i--)
{
if (str[i] > str[i + 1 ])
{
str[i]--;
for ( int j = i + 1 ; j < len; j++)
str[j] = '9' ;
}
}
return String.valueOf(str);
}
public static void main(String[] args)
{
String str = "11333445538" ;
int len = str.length();
System.out.println(tidyNum(str, len));
}
}
|
Python3
def tidyNum( str , len ):
for i in range ( len - 2 , - 1 , - 1 ):
if ( str [i] > str [i + 1 ]):
str [i] - = 1
for j in range (i + 1 , len ):
str [j] = 9
return str
str = [ 1 , 1 , 3 , 3 , 3 , 4 , 4 , 5 , 5 , 3 , 8 ]
len = len ( str )
num = tidyNum( str , len )
for i in range ( 0 , len ):
print ( str [i], end = "")
|
C#
using System;
class GFG
{
static String tidyNum(String str1, int len)
{
char [] str = str1.ToCharArray();
for ( int i = len - 2; i >= 0; i--)
{
if (str[i] > str[i + 1])
{
str[i]--;
for ( int j = i + 1; j < len; j++)
str[j] = '9' ;
}
}
string s = new string (str);
return s;
}
static void Main()
{
String str = "11333445538" ;
int len = str.Length;
Console.WriteLine(tidyNum(str, len));
}
}
|
PHP
<?php
function tidyNum( $str , $len )
{
for ( $i = $len - 2; $i >= 0; $i --)
{
if ( $str [ $i ] > $str [ $i + 1])
{
$x = ord( $str [ $i ]);
$x --;
$str [ $i ] = chr ( $x );
for ( $j = $i + 1; $j < $len ; $j ++)
$str [ $j ] = '9' ;
}
}
return $str ;
}
$str = "11333445538" ;
$len = strlen ( $str );
$num = tidyNum( $str , $len );
echo $num ;
?>
|
Javascript
<script>
function tidyNum(str1, len)
{
var str = str1.split( '' );
for (i = len - 2; i >= 0; i--)
{
if (str[i] > str[i + 1])
{
str[i]--;
for (j = i + 1; j < len; j++)
str[j] = '9' ;
}
}
return str.join( "" );
}
var str = "11333445538" ;
var len = str.length;
document.write(tidyNum(str, len));
</script>
|
Output:
11333444999
Share your thoughts in the comments
Please Login to comment...