Smallest number possible by swapping adjacent even odd pairs | C ++ 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 of 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; string findAns ( string s ) { int digit ; vector < int > odd ; vector < int > even ; for ( auto c : s ) { digit = c - '0' ; if ( digit & 1 ) odd . push_back ( digit ) ; else even . push_back ( digit ) ; } int i = 0 ; int j = 0 ; string ans = " " ; while ( i < odd . size ( ) and j < even . size ( ) ) { if ( odd [ i ] < even [ j ] ) ans += ( char ) ( odd [ i ++ ] + '0' ) ; else ans += ( char ) ( even [ j ++ ] + '0' ) ; } while ( i < odd . size ( ) ) ans += ( char ) ( odd [ i ++ ] + '0' ) ; while ( j < even . size ( ) ) ans += ( char ) ( even [ j ++ ] + '0' ) ; while ( ans [ 0 ] == '0' ) { ans . erase ( ans . begin ( ) ) ; } return ans ; } int main ( ) { string s = "894687536" ; cout << findAns ( s ) ; return 0 ; }