【Leetcode】【Easy】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
解题:
题目的意思是,比较版本号的大小,2版本比1版本大,而2.10版本比2.5版本大;
分别取出小数点前和小数点后的数字做比较;
代码:
1 class Solution { 2 public: 3 int compareVersion(string version1, string version2) { 4 int len1 = version1.size(); 5 int len2 = version2.size(); 6 int num1 = 0; 7 int num2 = 0; 8 int i = 0; 9 int j = 0; 10 while(i < len1 || j < len2) { 11 while (i < len1 && version1[i] != '.') { 12 num1 = num1 * 10 + (version1[i] - '0'); 13 i++; 14 } 15 16 while (j < len2 && version2[j] != '.') { 17 num2 = num2 * 10 + (version2[j] - '0'); 18 j++; 19 } 20 21 if(num1 > num2) 22 return 1; 23 else if (num1 < num2) 24 return -1; 25 26 num1 = 0; 27 num2 = 0; 28 i++; 29 j++; 30 } 31 32 return 0; 33 } 34 };