//return gia tri gan 0 nhat
using System;
using System.Linq;
class A
{
/// This method finds the number closest to zero.
public static int ClosestToZero(int[] ints)
{
foreach(int i in ints){
if(i < -2147483647 || i> 2147483647){
throw new ArgumentException("Out of Range!");
}
}
if(ints == null || ints.Length == 0){
throw new ArgumentException("ints can not null or empty");
}
var nearest = ints.OrderBy(x => Math.Abs((long) x - 0)).First();
int toReturn = nearest;
for(int i = 0; i < ints.Length; i++){
if(Math.Abs(ints[i]) == Math.Abs(nearest) && ints[i] > 0){
toReturn = ints[i];
}
}
return toReturn;
}
}
Aucun commentaire:
Enregistrer un commentaire