15 June 2018

play with numbers

Given an array as input, The condition is if the number is repeated you must add the number and put the next index value to 0. If the number is 0 print it at the last.

Eg: arr[] = { 0, 2, 2, 2, 0, 6, 6, 0, 8}
Output: 4 2 12 8 0 0 0 0 0 
  

public class NewClass24 {
    void print(int ar[],int n)
    {   int c=0;
        for(int i=0;i<n;i++)
        {
            if(ar[i]!=0)
            {
                System.out.print(ar[i]+" ");
            }else
            {
                c++;
            }
        }
        for(int i=0;i<c;i++)
            System.out.print(0+" ");
       
    }
 void repeat(int ar[],int n)
 {
     for(int i=0;i<n-1;i++)
     {
         if(ar[i]==ar[i+1])
         {
             ar[i]+=ar[i+1];
             ar[i+1]=0;
         }
     }
 }

 public static void main(String args[])
 {
     int ar[]={0,2,2,2,0,6,6,0,8};
     NewClass24 ob=new NewClass24();
     ob.repeat(ar,ar.length);
     ob.print(ar,ar.length);
 }
}

No comments:

Post a Comment