C++ solution (10 lines). very clean coding using istringstream to read input


  • 7
    L
     int compareVersion(string version1, string version2) {
        istringstream ver1(version1 + "."), ver2(version2 + ".");
        int val1 = 0, val2 = 0;
        char dot = '.';
        while (ver1.good() || ver2.good()) {
            if (ver1.good()) ver1 >> val1 >> dot;
            if (ver2.good()) ver2 >> val2 >> dot;
            if (val1 > val2) return 1;
            else if (val1 < val2) return -1;
            val1 = val2 = 0;
        }
        return 0;
    }

  • 0
    C

    istringstream and good() are quite nice! thanks.


  • 5
    Q

    stream.good() is not proper to determine the last read operation is successful or not. If eof is reached, .good() is false. The common way is to use the bool operator on stream. e.g. if (iss >> v) { ... }. I think the '.' appended is to get around the eof issue.

    int compareVersion(string version1, string version2) {
        istringstream iss1(version1), iss2(version2);
        while (iss1 || iss2) {
            char dot;
            long v1 = 0, v2 = 0;
            if (iss1) iss1 >> v1 >> dot;
            if (iss2) iss2 >> v2 >> dot;
            if (v1 != v2) {
                return v1 < v2 ? -1 : 1;
            }
        }
        return 0;
    }
    

  • 0
    L

    you are right, thanks for your advise. Your solution are more general to solve the reading input problem.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.