Coding Game - Temperature

本文介绍了一种算法,用于从一系列整数温度值中找出与零最接近的那个数。若两个数距离零等距,则优先选择正数。文章通过示例代码详细解释了解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Temperature

问题原址: TEMPERATURES,讲道理这个难度是四星就离谱,我觉得 1-2 差不多了……

题目分解

其实这道题就很简单了,就是读取一个数组,然后找到其中和 0 差值最小的值。

不过题目中给出了两个边界条件需要注意:

  1. Display 0 (zero) if no temperatures are provided. Otherwise, display the temperature closest to 0.

    当数组长度为 0 时返回 0,这也就是 for 循环体外的 if 做的事情了。

  2. 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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值