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
做题思路:
版本号被‘.’分为一个或多个部分,比较两个版本号时,先比较第一部分,若第一部分相同再比较第二部分,以此类推。
可以用Python对字符串的split功能把各个数字拆开,然后再将分割后的字符串转为数字进行比较。
如果两个版本号的数字数目不同,可以在短的后面补0直到数字数目相同,这样比较起来方便一些。
代码:
class Solution(object):
def compareVersion(self, version1, version2):
"""
:type version1: str
:type version2: str
:rtype: int
"""
v1 = version1.split('.')
v2 = version2.split('.')
maxlen = max(len(v1), len(v2))
while len(v1) < maxlen:
v1.append('0')
while len(v2) < maxlen:
v2.append('0')
for i in range(maxlen):
if int(v1[i]) > int(v2[i]):
return 1
elif int(v1[i]) < int(v2[i]):
return -1
return 0