Problem: Largest Even Number

*Difficulty: Easy

As usual Babul is back with his problem but this time with numbers. In his problem there is a number P (always a whole number) with N digits. Now he started finding out the largest possible even number formed by rearranging this N digit number. For example consider number 1324, after rearranging the digits the largest even number possible is 4312.

Note: In case the number does not contain any even digit then output the largest odd number possible.

Input:
The first line of input will contain an integer T which is the no. of test cases. Each of the next T lines will contain a number P.

Output:
For each test case in a new line print the required result.

Constraints:
1<=T<=100
1<=N<=1000

Example:
Input:

5
1324
3415436
1023422
03517
3555

Output:
4312
6543314
4322210
75310
5553

 

Implement: Python 2.7

def largest_even_number_from(n):
    l = list(map(int, n))
    l.sort(reverse=True)
    # if l contains only odd numbers 
    # return the maximum odd number possible 
    if len(filter(lambda x: int(x) % 2 != 0, l)) == len(l):
        return int(''.join(map(str, l)))
    # to make the largest even number formed by l
    # we put the smallest even number in l to the end of l 
    for _ in range(len(l)-1,-1,-1):
        if int(l[_]) % 2 == 0:
            l[_], l[-1] = l[-1], l[_]
            l = sorted(l[:-1], reverse=True) + [l[-1]]
            break
    return int(''.join(map(str, l)))

if __name__ == '__main__':
    t = input()
    for _ in range(t):
        n = raw_input().strip()
        print largest_even_number_from(n)
Advertisements