题目:
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
题意:
比较两个版本version1和version2的大小,如果version1>version2,返回1,如果version1<version2,返回-1,否则,返回0。
版本用.来隔开不同的版本号,如2.5,表示第一层版本号是2,第二层版本号是5.
代码:
class Solution(object):
def compareVersion(self, version1, version2):
"""
:type version1: str
:type version2: str
:rtype: int
"""
v1_list = version1.split('.') #去掉.,将各层的版本号取出
v2_list = version2.split('.')
len1 = len(v1_list)
len2 = len(v2_list)
for i in range(len1) : #将各层的版本号转化为int格式,便于比较
v1_list[i] = int(v1_list[i])
for i in range(len2) :
v2_list[i] = int(v2_list[i])
for i in range(min(len1,len2)) : #比较相同层的版本号
if v1_list[i] > v2_list[i] :
return 1
else :
if v1_list[i] < v2_list[i] :
return -1
if len1 < len2 : #判断是否version2的版本号比version1多
for j in range(len1,len2) :
if v2_list[j] > 0 :
return -1
if len1 > len2 : #判断是否version1的版本号比version2多
for j in range(len2,len1) :
if v1_list[j] > 0 :
return 1
return 0 #如果版本号层数相同,且都相等,返回0
笔记:
此题对版本号的格式处理有点麻烦
要考虑0,1.0 ,1.0.2.3 ,1.0.0.0等不同格式的版本号