[LeetCode165] Compare Version Numbers
题目:
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
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
分类:String
代码:
1 class Solution { 2 public: 3 int compareVersion(string version1, string version2) { 4 /* 5 vector<int> v1; 6 vector<int> v2; 7 istringstream ss1(version1); 8 istringstream ss2(version2); 9 while(!ss1.eof()) 10 { 11 string word; 12 getline(ss1,word,'.'); 13 int num; 14 stringstream ss; 15 ss << word; 16 ss >> num; 17 v1.push_back(num); 18 } 19 while(!ss2.eof()) 20 { 21 string word; 22 getline(ss2,word,'.'); 23 int num; 24 stringstream ss; 25 ss << word; 26 ss >> num; 27 v2.push_back(num); 28 } 29 30 for(int i = 0; i < max(v1.size(),v2.size()); ++i) 31 { 32 int num1,num2; 33 if(i < v1.size()) 34 num1 = v1[i]; 35 else 36 num1 = 0; 37 if(i < v2.size()) 38 num2 = v2[i]; 39 else 40 num2 = 0; 41 if(num1 > num2) 42 return 1; 43 else if(num1 < num2) 44 return -1; 45 } 46 return 0; 47 */ 48 49 stringstream ss1(version1),ss2(version2); 50 int num1 = 0, num2 = 0; 51 char op;//符号. 每次读入一个int 跳过. 52 53 while(!ss1.fail() || !ss2.fail()) 54 { 55 ss1 >> num1; 56 ss2 >> num2; 57 if(ss1.fail()) 58 num1 = 0; 59 if(ss2.fail()) 60 num2 = 0; 61 if(num1 < num2) 62 return -1; 63 else if(num1 > num2) 64 return 1; 65 ss1 >> op; 66 ss2 >> op; 67 } 68 69 return 0; 70 } 71 72 };