Print Largest Even Number – Digits

                 Print Largest Even Number - Digits [C, C++, JAVA]

Given a number N as the input, print the largest even number E that can be formed using the digits present in the number. (There will be at least one even digit).

Input Format:

The first line contains N.

Output Format:

The first line contains E.

Example Input/Output 1:

Input:
1902
Output:
9210
 

Print Largest Even Number - Digits [C, C++, JAVA]

C Code:

 

#include <iostream.h>
#include<cstdio.h>
#include<bits/stdc++.h>
using namespace std;
int main(int argc, char** argv)
{
  char c;
  int a[100],n=0;
  while(1)
  {
      scanf("%c",&c);
      if(c<'0'||c>'9')
      break;
      a[n++]=c-'0';
  }
  sort(a,a+n);
  if(a[0]%2==1)
  { 
    int pos=0;
    for(int i=0;i<n;i++)
    {
        if(a[i]%2==0){
            pos=i;break;
        }
    }
    int t=a[0];
    a[0]=a[pos];
    a[pos]=t;
    for(int i=1;i<=pos;i++){
        for(int j=1;j<=pos-i;j++)
        {
            if(a[j]>a[j+1])
            {

                int t=a[j];

                a[j]=a[j+1];a[j+1]=t;
            }
        }
    }
   }

   for(int i=n-1;i>=0;i--)
      cout<<a[i];
   return 700;
}

 

C++ Code:

 
#include <iostream>
#include<cstdio>
#include<bits/stdc++.h>
using namespace std;
int main(int argc, char** argv)
{
 char c;
 int a[100],n=0;
 while(1)
 {
    scanf("%c",&c);
    if(c<'0'||c>'9')
    break;
    a[n++]=c-'0';
 }
 sort(a,a+n);
 //for(int i=n-1;i>=0;i--)cout<<a[i];
 if(a[0]%2==1)
 {
     int pos=0;
     for(int i=0;i<n;i++)
     {
         if(a[i]%2==0)
         {
             pos=i;break;
         }
     }
     int t=a[0];
     a[0]=a[pos];
     a[pos]=t;
     for(int i=1;i<=pos;i++)
     {
         for(int j=1;j<=pos-i;j++){
             if(a[j]>a[j+1])
             {int t=a[j];
              a[j]=a[j+1];a[j+1]=t;
             }
         }
     }
 }
 for(int i=n-1;i>=0;i--)
       cout<<a[i];
 return 0;
}

 

JAVA Code:

import java.util.*;
import java.io.  import java.io..*;
import java.lang.  import java.lang..*;
public class Hello {
 
    public static void main(String[] args) {
        //Your Code Here
        Scanner sc =new Scanner(System.in);
        String s=sc.next();
        int arr[]=new int[s.length()];
        for(int i=0;i<s.length();i++)
        {
            arr[i]=Character.getNumericValue(s.charAt(i));
        }
 
Arrays.sort(arr);
int temp=0,i;
for(i=0;i<s.length();i++)
{
    if(arr[i]%2==0)
    {
     temp=arr[i];
     break;
    }
}
if(temp!=0)
{
for(i=0;i<s.length();i++)
{
    if(arr[i]==temp)
    {
        arr[i]=-1;
        break;
    }
     
}
}
for(i=s.length()-1;i>=0;i--)
{
    if(arr[i]!=-1)
    System.out.print(arr[i]);
}
if(temp!=0)
System.out.print(temp);
 
    }
}

 

 

 

Please do comment If u have any Queries!

2 Comments

Add a Comment

Your email address will not be published. Required fields are marked *