Find Closest Number to Zero LeetCode solution in C++

1
class Solution {
2
public:
3
int findClosestNumber(vector<int> &nums) {
4
// setting the ans to maximum value of int
5
int ans = INT_MAX;
6
for (int i : nums) {
7
// checking if each value of nums is less than the max value
8
if (abs(i) < abs(ans)) {
9
ans = i; // check for the lesser value
10
} else if (abs(i) == abs(ans)) {
11
ans = max(ans,
12
i); // return the maximum in cases there are multiple answers
13
}
14
}
15
return ans;
16
}
17
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0