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.
Example 1:
Input: version1 = "0.1", version2 = "1.1"
Output: -1
Example 2:
Input: version1 = "1.0.1", version2 = "1"
Output: 1
Example 3:
Input: version1 = "7.5.2.4", version2 = "7.5.3"
Output: -1
思路
将版本号以点号.
分开,借用强大的字符串流stringstream的功能来实现分段并转为整数,再依次进行比较。
这里用到istringstream的状态函数good,用来检查是否没有发生错误,例如是否可执行I/O操作,详见官方文档。
代码
class Solution {
public:
int compareVersion(string version1, string version2) {
istringstream v1(version1 + "."), v2(version2 + ".");
int d1 = 0, d2 = 0;
//int d1,d2;
char dot = '.';
while (v1.good() || v2.good()) {
//先赋值一个int,再赋值一个char
if (v1.good()) v1 >> d1 >> dot;
if (v2.good()) v2 >> d2 >> dot;
if (d1 > d2) return 1;
else if (d1 < d2) return -1;
//这里如果不重置为0的话,出现1.0.1和1这两个版本号的时候处理会出错
//第一个循环d1=d2=1, 第二个循环d1=0,d2没有值,仍为1,就出现了错误的结果
d1 = d2 = 0;
}
return 0;
}
};