---
# System prepended metadata

title: 0165. Compare Version Numbers
tags: [Leetcode, String, Medium]

---

# 0165. Compare Version Numbers
###### tags: `Leetcode` `Medium` `String`
Link: https://leetcode.com/problems/compare-version-numbers/description/
## 思路
注意如果在java里面写```string.split(".")```是不会起作用的 要写```string.split("\\.")``` 但在python里面这样写没问题
## Code
```python=
class Solution:
    def compareVersion(self, version1: str, version2: str) -> int:
        split1 = version1.split(".")
        split2 = version2.split(".")
        for i in range(max(len(split1), len(split2))):
            num1 = int(split1[i]) if i<len(split1) else 0
            num2 = int(split2[i]) if i<len(split2) else 0
            if num1<num2: 
                return -1
            elif num1>num2: 
                return 1
        return 0
```
```java=
class Solution {
    public int compareVersion(String version1, String version2) {
        String[] split1 = version1.split("\\.");
        String[] split2 = version2.split("\\.");
        for(int i=0; i<Math.max(split1.length, split2.length); i++){
            int num1 = i<split1.length?Integer.valueOf(split1[i]):0;
            int num2 = i<split2.length?Integer.valueOf(split2[i]):0;
            if(num1<num2) return -1;
            else if(num1>num2) return 1; 
        }
        return 0;
    }
}
```