Given a long integer, return the smallest(magnitude) integer permutation of that number.
Examples:
Input : 5468001
Output : 1004568
Input : 5341
Output : 1345
Approach : As number is long, store the number as string, sort the string, if there is no leading zero, return this string, if there is any leading zero, swap first element of string with first non-zero element of string, and return the string.
Below is the implementation of above approach :
#include <bits/stdc++.h>
using namespace std;
string findSmallestPermutation(string s)
{
int len = s.length();
sort(s.begin(), s.end());
int i = 0;
while (s[i] == '0' )
i++;
swap(s[0], s[i]);
return s;
}
int main()
{
string s = "5468001" ;
string res = findSmallestPermutation(s);
cout << res << endl;
return 0;
}
|
Output:
1004568
import java.util.Arrays;
public class GFG {
static char [] findSmallestPermutation(String s1)
{
char s[] = s1.toCharArray();
Arrays.sort(s);
int i = 0 ;
while (s[i] == '0' )
i++;
char temp = s[ 0 ];
s[ 0 ] = s[i];
s[i] = temp;
return s;
}
public static void main(String args[])
{
String s = "5468001" ;
char res[] = findSmallestPermutation(s);
System.out.println(res);
}
}
|
Output:
1004568
def sort_string(a):
return ''.join( sorted (a))
def findSmallestPermutation(s):
le = len (s)
s = sort_string(s)
i = 0
while (s[i] = = '0' ):
i + = 1
a = list (s)
a[ 0 ] = a[i]
a[i] = '0'
s = "".join(a)
return s
s = "5468001"
res = findSmallestPermutation(s)
print res
|
Output:
1004568
Comments
Post a Comment