diff --git a/solutions/165. Compare Version Numbers.md b/solutions/165. Compare Version Numbers.md index 5a62451..a87d829 100644 --- a/solutions/165. Compare Version Numbers.md +++ b/solutions/165. Compare Version Numbers.md @@ -18,6 +18,11 @@ 这里我们使用istringstream。 +学习几个这里需要用到的stringstream的成员函数: +* `good()`: 判断是否没有错误; +* `bad()`: 与`good()`相反,判断是否存在错误; +* `eof()`: 判断是否到达end-of-file; + **注意学习这种将字符串按照某个字符分割开的处理方法!!!** @@ -48,20 +53,24 @@ public: ## 思路二 ``` C++ -class Solution { +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; + + # 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 num1 > num2 ? 1 : -1; - } + if(num1 > num2) return 1; + else if(num1 < num2) return -1; + } + return 0; } };