Write a program to Find The Closest Number To 0

Write a program to Find The Closest Number To 0.

public static int getClosestToZero(int[] a){
  
          int num = a[0];
         
          int absNum = Math.abs(num);


          for(int i = 1; i < a.length; ++i) 
          {  
             
             
              int newAbs = Math.abs(a[i]);

              if(newAbs < absNum) 
              {

                  absNum = newAbs;
                  num = a[i];

                 }   
               else if(newAbs==absNum)
               {
               if(num<a[i])
               {
                 num=a[i];
               }
          }
            }
      return num;
}

Add a Comment

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

17 − four =