Question: https://leetcode.com/problems/compare-version-numbers/
Question Name: Compare Version Numbers
Clean up the tailing 0(s), and the right answer is there.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | class Solution: # @param version1, a string # @param version2, a string # @return an integer def compareVersion(self, version1, version2): # Split the version number with dot, and clear the tailing 0(s) versionList1 = [int(ver) for ver in version1.split(".")] while len(versionList1) > 1 and versionList1[-1] == 0: versionList1.pop() versionList2 = [int(ver) for ver in version2.split(".")] while len(versionList2) > 1 and versionList2[-1] == 0: versionList2.pop() shorterVersion = min(len(versionList1), len(versionList2)) # Compare the common part of version numbers. for i in xrange(shorterVersion): if versionList1[i] > versionList2[i]: return 1 elif versionList1[i] < versionList2[i]: return -1 # Check the remaining part of version number. if len(versionList1) != shorterVersion: return 1 elif len(versionList2) != shorterVersion: return -1 else: return 0 |