题目描述:

image-20250120211212045

思路:遍历,基础没什么多说的

package January;


/**
* @author hxw
* @version 1.0
* @date 2025/1/20 21:03
* @description: 2239. 找到最接近 0 的数字 简单
*/
public class twenty {
public static void main(String[] args) {
int[] nums = {-4, -1, 1, 2, 3};
int result = Solution.findClosestNumber(nums);
System.out.println(result);

}

class Solution {
public static int findClosestNumber(int[] nums) {
int result = nums[0];
for (int num : nums) {
if (Math.abs(num) < Math.abs(result) || (Math.abs(num) == Math.abs(result) && num > result)) {
result = num;
}
}
return result;
}

}
}