python算法丨LeetCode165-比较版本号

165.比较两个版本号 version1 和 version2。

如果 version1 > version2 返回 1,如果 version1 < version2 返回 -1, 除此之外返回 0。
你可以假设版本字符串非空,并且只包含数字和 . 字符。
. 字符不代表小数点,而是用于分隔数字序列。

  • 示例 1: 输入: version1 = “0.1”, version2 = “1.1” 输出: -1
  • 示例 2:输入: version1 = “1.0.1”, version2 = “1” 输出: 1
  • 示例 3: 输入: version1 = “7.5.2.4”, version2 = “7.5.3” 输出: -1
def fun(v1, v2):
    l_1 = v1.split('.')
    l_2 = v2.split('.')
    c = 0
    while True:
        if c == len(l_1) and c == len(l_2):
            return 0
        if len(l_1) == c:
            l_1.append(0)
        if len(l_2) == c:
            l_2.append(0)
        if int(l_1[c]) > int(l_2[c]):
            return 1
        elif int(l_1[c]) < int(l_2[c]):
            return -1
        c += 1


print(fun("1.0.1", "1"))

猜你喜欢

转载自blog.csdn.net/weixin_40687614/article/details/108734490
今日推荐