# 165. Compare Version Numbers [easy] (Python)

## 题目链接

https://leetcode.com/problems/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

## 思路方法

1 等于 1.0 等于 1.0.000.00
1 等于 01 等于 000001
1.1 小于 1.10 小于 1.100000

### 思路一

class Solution(object):
def compareVersion(self, version1, version2):
"""
:type version1: str
:type version2: str
:rtype: int
"""
v1_list = version1.split('.')
v2_list = version2.split('.')

for i in range(0, max(len(v1_list), len(v2_list))):
v1 = int(v1_list[i]) if len(v1_list) > i else 0
v2 = int(v2_list[i]) if len(v2_list) > i else 0
if v1 > v2:
return 1
elif v1 < v2:
return -1
return 0

class Solution(object):
def compareVersion(self, version1, version2):
"""
:type version1: str
:type version2: str
:rtype: int
"""
v1_list = [int(v) for v in version1.split('.')]
v2_list = [int(v) for v in version2.split('.')]
max_len = max(len(v1_list), len(v2_list))
if len(v1_list) == max_len:
v2_list += [0]*(max_len - len(v2_list))
else:
v1_list += [0]*(max_len - len(v1_list))

if v1_list != v2_list:
return 0
else:
return 1 if v1_list > v2_list else -1

### 思路二

class Solution(object):
def compareVersion(self, version1, version2):
"""
:type version1: str
:type version2: str
:rtype: int
"""
if version1 == version2:
return 0

ind_1 = version1.find('.')
ind_2 = version2.find('.')
part_1 = version1[0:ind_1] if ind_1 != -1 else version1
part_2 = version2[0:ind_2] if ind_2 != -1 else version2

if int(part_1) == int(part_2):
remain_1 = version1[len(part_1)+1:] if version1[len(part_1)+1:] != '' else '0'
remain_2 = version2[len(part_2)+1:] if version2[len(part_2)+1:] != '' else '0'
return self.compareVersion(remain_1, remain_2)
else:
return 1 if int(part_1) > int(part_2) else -1

PS: 新手刷LeetCode，新手写博客，写错了或者写的不清楚还请帮忙指出，谢谢！

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120