Created
October 6, 2024 13:05
-
-
Save mohneesh7/36cf99444d1d34e45e2e7907cfe1e22a to your computer and use it in GitHub Desktop.
Solution for Find Closest Number to Zero
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution: | |
def diff_of_num(self, num): | |
if num <= 0: | |
return -num | |
else: | |
return num | |
def findClosestNumber(self, nums): | |
closest = nums[0] | |
for x in nums: | |
# check if its closest | |
if self.diff_of_num(x) < self.diff_of_num(closest): | |
closest = x | |
# if x == closest, return max(x,closest) yet to optimized | |
if self.diff_of_num(x) == self.diff_of_num(closest): | |
closest = max(x,closest) | |
return closest |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment