Compare two version numbers version1 and version2.
If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0.git
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.ide
Here is an example of version numbers ordering:spa
0.1 < 1.1 < 1.2 < 13.37
思路:code
以 . 爲分隔符分割數字,依次對比大小。注意兩個版本號長度不同的狀況。three
int compareVersion(string version1, string version2) { int i = 0, j = 0; int n1 = 0, n2 = 0; while(i < version1.size() && j < version2.size()) //對比每個小數點前對應的數字 { n1 = 0, n2 = 0; while(i < version1.size() && version1[i++] != '.') n1 = n1 * 10 + version1[i - 1] - '0'; while(j < version2.size() && version2[j++] != '.') n2 = n2 * 10 + version2[j - 1] - '0'; if(n1 > n2) return 1; if(n1 < n2) return -1; } //處理數字數量不同多的狀況 如 1.0 和 1 或 1.0.0.4 和 1.0 此時確定比較短的那個版本號已經到頭了 只要獲取剩下的那個版本號後面的數字是否有大於0的便可 n1 = 0, n2 = 0; while(i++ < version1.size()) n1 = (version1[i - 1] == '.') ? n1 : n1 * 10 + version1[i - 1] - '0'; while(j++ < version2.size()) n2 = (version2[j - 1] == '.') ? n2 : n2 * 10 + version2[j - 1] - '0'; if(n1 > n2) return 1; else if(n1 < n2) return -1; else return 0; }
大神的代碼,簡潔不少。至關於把個人代碼下面的循環部分和上面的融合在一塊兒了。ci
public class Solution { public int compareVersion(String version1, String version2) { String[] v1 = version1.split("\\."); String[] v2 = version2.split("\\."); int longest = v1.length > v2.length? v1.length: v2.length; for(int i=0; i<longest; i++) { int ver1 = i<v1.length? Integer.parseInt(v1[i]): 0; int ver2 = i<v2.length? Integer.parseInt(v2[i]): 0; if(ver1> ver2) return 1; if(ver1 < ver2) return -1; } return 0; } }