leetcode 165 Compare Version Numbers
阿新 • • 發佈:2019-02-08
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
Here is an example of version numbers ordering:
0.1 < 1.1 < 1.2 < 13.37
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
class Solution { public: int compareVersion(string version1, string version2) { int a1 = 0, a2 = 0, b1 = 0, b2 = 0; if(version1=="" && version2=="") return 0; int index1 = version1.find('.'), index2 = version2.find('.'); if(index1==string::npos) { a1 = atoi(version1.c_str()); index1 = version1.size()-1; } else { a1 = atoi(version1.substr(0, index1).c_str()); } if(index2==string::npos) { a2 = atoi(version2.c_str()); index2 = version2.size()-1; } else { a2 = atoi(version2.substr(0, index2).c_str()); } if(a1 > a2) return 1; else if(a1 < a2) return -1; return compareVersion(version1.substr(index1+1), version2.substr(index2+1)); } };