mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Update 165. Compare Version Numbers.md
This commit is contained in:
parent
b60b313305
commit
e3873d8e74
@ -18,6 +18,11 @@
|
||||
|
||||
这里我们使用istringstream。
|
||||
|
||||
学习几个这里需要用到的stringstream的成员函数:
|
||||
* `good()`: 判断是否没有错误;
|
||||
* `bad()`: 与`good()`相反,判断是否存在错误;
|
||||
* `eof()`: 判断是否到达end-of-file;
|
||||
|
||||
**注意学习这种将字符串按照某个字符分割开的处理方法!!!**
|
||||
|
||||
|
||||
@ -51,17 +56,21 @@ public:
|
||||
class Solution {
|
||||
public:
|
||||
int compareVersion(string version1, string version2) {
|
||||
istringstream v1(version1 + '.'), v2(version2 + '.');
|
||||
istringstream is1(version1 + '.'), is2(version2 + '.');
|
||||
int num1, num2;
|
||||
char dot = '.';
|
||||
while(v1.good() || v2.good()){ // 函数good判断输入流是否good
|
||||
num1 = 0; num2 = 0;
|
||||
if(v1.good()) v1 >> num1 >> dot;
|
||||
if(v2.good()) v2 >> num2 >> dot;
|
||||
char cdot;
|
||||
|
||||
if(num1 != num2)
|
||||
return num1 > num2 ? 1 : -1;
|
||||
# define OK1 is1.good() // 或者 !is1.fail(), !is1.eof()
|
||||
# define OK2 is2.good()
|
||||
while(OK1 || OK2){
|
||||
num1 = num2 = 0;
|
||||
if(OK1) is1 >> num1 >> cdot;
|
||||
if(OK2) is2 >> num2 >> cdot;
|
||||
|
||||
if(num1 > num2) return 1;
|
||||
else if(num1 < num2) return -1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
|
Loading…
Reference in New Issue
Block a user