Leetcode Note: Go - Find Closest Number to Zero
Find Closest Number to Zero - LeetCode
https://leetcode.com/problems/find-closest-number-to-zero/
- Go 言語で取り組んだメモ
回答
Find Closest Number to Zero - LeetCode
https://leetcode.com/problems/find-closest-number-to-zero/solutions/3154753/go/
func findClosestNumber(nums []int) int {
closestNumber := -math.MaxInt
closestAbsNumber := math.MaxInt
for _, num := range nums {
diff := int(math.Abs(float64(num)))
if diff < closestAbsNumber {
closestAbsNumber = diff
closestNumber = num
} else if diff == closestAbsNumber {
closestNumber = max(closestNumber, num)
}
}
return closestNumber
}
// max returns larger digit
func max(num1, num2 int) int {
if num1 < num2 {
return num2
}
return num1
}