Temperature
问题原址: TEMPERATURES,讲道理这个难度是四星就离谱,我觉得 1-2 差不多了……
题目分解
其实这道题就很简单了,就是读取一个数组,然后找到其中和 0 差值最小的值。
不过题目中给出了两个边界条件需要注意:
-
Display 0 (zero) if no temperatures are provided. Otherwise, display the temperature closest to 0.
当数组长度为 0 时返回 0,这也就是
for
循环体外的if
做的事情了。 -
If two numbers are equally close to zero, positive integer has to be considered closest to zero (for instance, if the temperatures are -5 and 5, then display 5).
当两个值的差值一样是,取正数而非负数。
这个就是
else if
里面做的判断了。
解法
总之这道题就不是很难,解法如下:
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
const n = parseInt(readline()); // the number of temperatures to analyse
var inputs = readline().split(" ");
// one variable holds the closest temperature
// another one hold the difference between current temp and 0 in positive value
let closestTemp = Number.MAX_VALUE,
closestdiffTemp = Number.MAX_VALUE;
if (n === 0) {
// edge case as per requirment
closestTemp = 0;
}
for (let i = 0; i < n; i++) {
const t = parseInt(inputs[i]); // a temperature expressed as an integer ranging from -273 to 5526
const currDiffTemp = Math.abs(t);
// replace the value if current temp diff is smaller
if (currDiffTemp < closestdiffTemp) {
closestdiffTemp = currDiffTemp;
closestTemp = t;
} else if (currDiffTemp === closestdiffTemp) {
// keep positive val as per requirement
closestTemp = t > 0 ? t : closestTemp;
}
}
// Write an answer using console.log()
// To debug: console.error('Debug messages...');
console.log(closestTemp);