165. 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 int temp1; 5 int temp2; 6 int i = 0; 7 int j = 0; 8 while (i < version1.length() || j < version2.length()) 9 { 10 temp1 = 0; 11 temp2 = 0; 12 // 13 while (i < version1.length() && '.' != version1[i]) 14 { 15 temp1 = temp1 * 10 + (version1[i] - '0'); 16 i++; 17 } 18 i++; 19 // 20 while (j < version2.length() && '.' != version2[j]) 21 { 22 temp2 = temp2 * 10 + (version2[j] - '0'); 23 j++; 24 } 25 j++; 26 if (temp1 > temp2) 27 { 28 return 1; 29 } 30 if (temp1 < temp2) 31 { 32 return -1; 33 } 34 } 35 return 0; 36 } 37 };