Find Closest Number to Zero LeetCode solution in C++
1class Solution {2public:3int findClosestNumber(vector<int> &nums) {4// setting the ans to maximum value of int5int ans = INT_MAX;6for (int i : nums) {7// checking if each value of nums is less than the max value8if (abs(i) < abs(ans)) {9ans = i; // check for the lesser value10} else if (abs(i) == abs(ans)) {11ans = max(ans,12i); // return the maximum in cases there are multiple answers13}14}15return ans;16}17};