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

  1. int compareVersion(string version1, string version2) {
  2. int vlen1 = version1.size();
  3. int vlen2 = version2.size();
  4. if(vlen1==0 && vlen2==0) return 0;
  5. stringstream s1(version1);
  6. stringstream s2(version2);
  7. vector<int> value1;
  8. vector<int> value2;
  9. string tmpvalue;
  10. while(getline(s1,tmpvalue,'.')) {
  11. value1.push_back(atoi(tmpvalue.c_str()));
  12. }
  13. while(getline(s2,tmpvalue,'.')) {
  14. value2.push_back(atoi(tmpvalue.c_str()));
  15. }
  16. int val_len1 = value1.size();
  17. int val_len2 = value2.size();
  18. int i = 0;
  19. int j = 0;
  20. while(i<val_len1 || j < val_len2) {
  21. int real_1 = 0;
  22. int real_2 = 0;
  23. if(i<val_len1) real_1 = value1[i];
  24. if(j<val_len2) real_2 = value2[j];
  25. if(real_1 > real_2) return 1;
  26. else if(real_1 < real_2) return -1;
  27. i++;
  28. j++;
  29. }
  30. return 0;
  31. }

   学习:

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,所以要控制

posted @ 2014-12-16 16:08  purejade  阅读(113)  评论(0)    收藏  举报