Skip to content

Latest commit

 

History

History
62 lines (50 loc) · 1.61 KB

File metadata and controls

62 lines (50 loc) · 1.61 KB
  1. Compare Version Numbers
Compare two version numbers version1 and version2.
If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0.

You may assume that the version strings are non-empty and contain only digits and the . character.
The . character does not represent a decimal point and is used to separate number sequences.
For instance, 2.5 is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision.

Here is an example of version numbers ordering:

0.1 < 1.1 < 1.2 < 13.37
Credits:
Special thanks to @ts for adding this problem and creating all test cases.

my thoughts:

1. split version into integers, compare from most significant to the least significant int.
*tricky part: trailing 0's.

my solution:

**********
class Solution:
    def compareVersion(self, version1, version2):
        """
        :type version1: str
        :type version2: str
        :rtype: int
        """
        if not version1 or not version2 or version1 == version2:
            return 0
        
        v1 = [int(i) for i in version1.split('.')]
        v2 = [int(i) for i in version2.split('.')]
        
        l = min( len(v1), len(v2) )
        
        i = 0
        while i < l:
            if v1[i] > v2[i]:
                return 1
            elif v1[i] < v2[i]:
                return -1
            i += 1
            
        if len(v1) > l and sum(v1[l:]) > 0:
            return 1
        if len(v2) > l and sum(v2[l:]) > 0:
            return -1
        return 0

my comments:


from other ppl's solution:

1. N/A