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 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.
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.
简单,但不好写,需要细心
特例:1.0 1 1.0.0.0 1.0
- int compareVersion(string version1, string version2) {
- int vlen1 = version1.size();
- int vlen2 = version2.size();
- if(vlen1==0 && vlen2==0) return 0;
- stringstream s1(version1);
- stringstream s2(version2);
- vector<int> value1;
- vector<int> value2;
- string tmpvalue;
- while(getline(s1,tmpvalue,'.')) {
- value1.push_back(atoi(tmpvalue.c_str()));
- }
- while(getline(s2,tmpvalue,'.')) {
- value2.push_back(atoi(tmpvalue.c_str()));
- }
- int val_len1 = value1.size();
- int val_len2 = value2.size();
- int i = 0;
- int j = 0;
- while(i<val_len1 || j < val_len2) {
- int real_1 = 0;
- int real_2 = 0;
- if(i<val_len1) real_1 = value1[i];
- if(j<val_len2) real_2 = value2[j];
- if(real_1 > real_2) return 1;
- else if(real_1 < real_2) return -1;
- i++;
- j++;
- }
- return 0;
- }
学习:
size_t find (const string& str, size_t pos = 0) const;
size_t 为unsigned int, 如果找不到,则返回string::npos(无符号整数最大值)
string substr (size_t pos = 0, size_t len = npos) const;
pos 最大为len,如果大于,则返回out_of_range,所以要控制

浙公网安备 33010602011771号