LeetCode-Compare Version Numbers
Compare two version numbers version1 and version1.
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.
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 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
When I first got a question, I understood it for a long time.
In fact, the meaning is very simple. Each string contains numbers and '.', '.' only serves to separate the numbers and then compare the sizes in sequence.
In the method that you write, we simply break down two strings into the corresponding vector. Here are a few notes.
The numbers in the two strings are not of the same length.
11.22.33.00.00000 = 11.22.33
11.22.33.01> 11.22.33
The character string does not have the '.' symbol at the end.
class Solution {public: int compareVersion(string version1, string version2) { vector
ver1;vector
ver2;int val1 = 0,val2 = 0;int i = 0,j = 0;while (i < version1.length()){if(version1[i] != '.'){val1 = val1*10+(version1[i]-'0');}else{ver1.push_back(val1);val1 = 0;}i++;}while (j < version2.length()){if (version2[j] != '.'){val2 = val2*10+(version2[j]-'0');}else{ver2.push_back(val2);val2 = 0;}j++;}ver1.push_back(val1);ver2.push_back(val2);bool flag = ver1.size() <= ver2.size();int length = flag? ver1.size():ver2.size();for (i = 0; i < length; i++){if (ver1[i] > ver2[i]){return 1;}else if(ver1[i] < ver2[i]){ return -1;}}if (flag){for (i = length; i < ver2.size(); i++){if (ver2[i] != 0){return -1;}}return 0;}else{for (i = length; i < ver1.size(); i++){if (ver1[i] != 0){return 1;}}return 0;} }};
The following are some other algorithms on the Internet, which are similar in thinking. However, it is much easier to just loop the code in the while loop:
class Solution {public: int compareVersion(string version1, string version2) { int lev1=0,lev2=0; int id1=0,id2=0; while(id1!=version1.length()||id2!=version2.length()){ lev1=0; while(id1
lev2){ return 1; }else if(lev1