Java solution
import java.math.*;
class Solution {
static double closestToZero(double[] ts) {
if (ts.length == 0) return 0;
double closest = ts[0];
for (double i : ts) {
double abs = Math.abs(i);
double absClosest = Math.abs(closest);
if (abs < absClosest) {
closest = i;
} else if (abs == absClosest && closest < 0) {
closest = i;
}
}
return closest;
}
}
C# solution
using System;
class Solution
{
public static double ClosestToZero(double[] ts)
{
if (ts.Length == 0) return 0;
var closest = ts[0];
foreach (double d in ts)
{
double abs = Math.Abs(d);
double absClosest = Math.Abs(closest);
if (abs < absClosest)
{
closest = d;
}
else if (abs == absClosest && closest < 0)
{
closest = d;
}
}
return closest;
}
}
C# solution 2 (Linq powered, thanks to Josh)
using System;
using System.Linq;
class Solution
{
public static double ClosestToZero(double[] ts)
{
double result = 0;
if(ts.Length > 0)
{
result = ts
.OrderBy(i=> Math.Abs(i))
.GroupBy(i=> Math.Abs(i))
.First()
.Max();
}
return result;
}
}
C# solution 3 (Linq powered, thanks to Benjamin)
using System;
using System.Linq;
class Solution
{
public static double ClosestToZero(double[] ts)
{
if(ts.Length == 0)
return 0;
return ts.OrderBy(t => Math.Abs(t)).ThenBy(t => -t).First();
}
}
PHP solution
<?php
function closestToZero(array $ts)
{
if (count($ts) === 0) return 0;
$closest = $ts[0];
foreach ($ts as $d)
{
$absD = abs($d);
$absClosest = abs($closest);
if ($absD < $absClosest)
{
$closest = $d;
}
else if ($absD === $absClosest && $closest < 0)
{
$closest = $d;
}
}
return $closest;
}
?>
C solution
#include <math.h>
double closest_to_zero(double ts[], int size)
{
double res = 0;
if (size > 0){
res = ts[0];
for (int i = 1; i < size; i++){
if (fabs(res) > fabs(ts[i])){
res = ts[i];
}
else if (fabs(res) == fabs(ts[i]) && (ts[i] > 0)){
res = ts[i];
}
}
}
return res;
}