First, the numbers are arranged in ascending order. If there is no leading zero and an odd number, the numbers are output directly. If there is a leading zero,-1 is output. In addition, if the ending number is an even number, find the first odd number from the back to the front, move the number behind it one time forward, and put the odd number to the end.
It is worth noting that when the input is 960, this method will obtain a number with a leading zero. Therefore, it is necessary to determine whether the first priority is zero after moving.
The Code is as follows:
1 #define MAXN 101 2 #include <stdlib.h> 3 #include <iostream> 4 #include <cstdio> 5 #include <algorithm> 6 using namespace std; 7 int arr[MAXN]; 8 int N; 9 bool comp(int a, int b)10 {11 return a>b;12 }13 14 void p(int *a)15 {16 for( int i = 0 ; i < N ; i++ )17 {18 printf("%d", a[i]);19 }20 printf("\n");21 }22 void solve()23 {24 sort(arr, arr+N, comp); 25 if( arr[N-1] & 1 && arr[0] != 0)26 {27 p(arr);28 }29 else if( arr[0] == 0 )30 {31 printf("%d\n", -1);32 }33 else34 {35 for( int i = N-2 ; i >= 0 ; i-- )36 {37 if( arr[i] & 1 )38 {39 int tmp = arr[i];40 for( int j = i+1 ; j <= N-1 ; j++ )41 {42 arr[j-1] = arr[j];43 }44 arr[N-1] = tmp;45 break;46 }47 }48 if( arr[N-1] & 1 && arr[0] != 0)49 {50 p(arr);51 }52 else53 {54 printf("%d\n", -1);55 }56 }57 }58 int main(int argc, char *argv[])59 {60 while( scanf("%d", &N ) != EOF)61 {62 for( int i = 0 ; i < N ; i++ )63 {64 scanf("%d", &arr[i]);65 }66 solve();67 }68 return 0;69 }
HDU 5055 Bob and Math Problem