Maximum possible number with the given operation
Last Updated :
19 Mar, 2022
Given a positive integer N, the task is to convert this integer to the maximum possible integer without leading zeroes by changing the digits. A digit X can only be changed into a digit Y if X + Y = 9.
Examples:
Input: N = 42
Output: 57
Change 4 -> 5 and 2 -> 7.
Input: N = 1
Output: 8
Approach: Only the digits which are greater than or equal to 5 need to be changed as changing the digits which are less than 5 will result in a larger number. After all the required digits have been updated, check whether the resultant number has a leading zero, if yes then change it to a 9.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
string maxInt(string str)
{
for ( int i = 0; i < str.length(); i++) {
if (str[i] < '5' ) {
str[i] = ( '9' - str[i]) + '0' ;
}
}
if (str[0] == '0' )
str[0] = '9' ;
return str;
}
int main()
{
string str = "42" ;
cout << maxInt(str);
return 0;
}
|
Java
class GFG
{
static String maxInt( char str[])
{
for ( int i = 0 ; i < str.length; i++)
{
if (str[i] < '5' )
{
str[i] = ( char )(( '9' - str[i]) + '0' );
}
}
if (str[ 0 ] == '0' )
str[ 0 ] = '9' ;
String str2 = new String(str);
return str2;
}
public static void main (String[] args)
{
String str = "42" ;
System.out.println(maxInt(str.toCharArray()));
}
}
|
Python3
def maxInt(string):
string2 = ""
for i in range ( 0 , len (string)):
if (string[i] < '5' ):
string2 + = str (( ord ( '9' ) - ord (string[i])))
else :
string2 + = str (string[i])
if (string2[ 0 ] = = '0' ):
string2[ 0 ] = '9'
return string2
if __name__ = = '__main__' :
string = "42"
print (maxInt(string))
|
C#
using System;
class GFG
{
static String maxInt( char []str)
{
for ( int i = 0; i < str.Length; i++)
{
if (str[i] < '5' )
{
str[i] = ( char )(( '9' - str[i]) + '0' );
}
}
if (str[0] == '0' )
str[0] = '9' ;
String str2 = new String(str);
return str2;
}
public static void Main (String []args)
{
String str = "42" ;
Console.WriteLine(maxInt(str.ToCharArray()));
}
}
|
Javascript
<script>
function maxInt(str)
{
var str2 = "" ;
for ( var i = 0; i < str.length; i++) {
if (str[i] < '5' ) {
var l = ( '9' .charCodeAt(0) - str[i].charCodeAt(0)) + '0' .charCodeAt(0);
str2 = str2.concat(String.fromCharCode(l));
}
}
if (str2[0] == '0' )
str2[0] = '9' ;
return str2;
}
var str = "42" ;
document.write(maxInt(str))
</script>
|
Time Complexity: O(|str|)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...