Smallest number possible by swapping adjacent even odd pairs | Java program to find the smallest number possible by swapping adjacent digits of different parity ; Function to return the smallest number possible ; Arrays to store odd and even digits in the order their appearance in the given String ; Insert the odd and even digits ; Pointer to odd digit ; Pointer to even digit ; In case number of even and odd digits are not equal If odd digits are remaining ; If even digits are remaining ; Removal of leading 0 's ; Driver code
import java . util . * ; class GFG { static String findAns ( String s ) { int digit ; Vector < Integer > odd = new Vector < Integer > ( ) ; Vector < Integer > even = new Vector < Integer > ( ) ; for ( char c : s . toCharArray ( ) ) { digit = c - '0' ; if ( digit % 2 == 1 ) odd . add ( digit ) ; else even . add ( digit ) ; } int i = 0 ; int j = 0 ; String ans = " " ; while ( i < odd . size ( ) && j < even . size ( ) ) { if ( odd . get ( i ) < even . get ( j ) ) ans += ( char ) ( odd . get ( i ++ ) + '0' ) ; else ans += ( char ) ( even . get ( j ++ ) + '0' ) ; } while ( i < odd . size ( ) ) ans += ( char ) ( odd . get ( i ++ ) + '0' ) ; while ( j < even . size ( ) ) ans += ( char ) ( even . get ( j ++ ) + '0' ) ; while ( ans . charAt ( 0 ) == '0' ) { ans = ans . substring ( 1 ) ; } return ans ; } public static void main ( String [ ] args ) { String s = "894687536" ; System . out . print ( findAns ( s ) ) ; } }