Closest to Zero

 You have been given an integer array A of size N . You need to print the number with the value closest to zero . If there are multiple elements , print the number with the greater value.

Input Format:

  • First Line: An integer N denoting  the size  of the array A.
  • Next Line: N  space - separated integers denoting the elements of the array A
Output Format:

Print the value  of the element closest to zero . If there  are multiple candidates, then  print the number  with greater value.

Constraints

1<=N<=100

1<=|Ai|<=100 , where |Ai| denotes the absolute value of Ai


Sample input : 

5

0 2 3 4 5

Sample output :

0

Solution :- 

C# 

using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;


public class HelloWorld
{
static public void Main()
{
String line;
line = Console.ReadLine();
int N = Convert.ToInt32(line);
line = Console.ReadLine();
int[] A = new int[N];
A = line.Split().Select(str => int.Parse(str)).ToArray();

int out_ = homeWork(N, A);
Console.Out.WriteLine(out_);
}

static int homeWork(int N, int[] A)
{
int delta = 0;
int beta = 0;
        Array.Sort(A);
        
        Console.WriteLine(" ");
        
for(int i = 0 ; i< N; i++)
{       
delta = (Math.Abs(A[i])-0);
if(i == 0)
{
beta = A[i];
}
if((delta <= Math.Abs(beta)) && (A[i] >=0) )
{
beta = A[i];
}
            if((delta > Math.Abs(beta)) && (A[i] < 0) )
{
beta = A[i];
}
}
return beta;
}
}



Comments