10 line concise solution. (C++)


  • 39
    A

    This is a concise solution using stringstream to format string into int.

    int compareVersion(string version1, string version2) {
        for(auto& w : version1) if (w == '.') w=' ';
        for(auto& w : version2) if (w == '.') w=' ';
        istringstream s1(version1), s2(version2);
        while(1) {
            int n1,n2;
            if (not(s1 >> n1) ) n1 = 0;
            if (not(s2 >> n2) ) n2 = 0;
            if (not s1 and not s2) return 0;
            if (n1<n2) return -1;
            if (n1>n2) return 1;
        }
    }

  • 0
    R

    I like your solution!


  • 0
    Q

    nice, an good way, thanks. I used sscanf with wth almost same simplicity. simple 9 lines solution with sscanf


  • 2
    S

    Based on your code, removed replacing '.' with ' ' part.

    class Solution {
    public:
    int compareVersion(string version1, string version2) {
        istringstream s1(version1), s2(version2);
    
    while(1) {
        int n1,n2;
        string tmp1, tmp2;
        if (!getline(s1, tmp1, '.')) n1 = 0; 
        else n1 = stoi(tmp1);
        if (!getline(s2,tmp2,'.')) n2=0;
        else n2 = stoi(tmp2);
        if (not s1 and not s2) return 0;
        if (n1<n2) return -1;
        if (n1>n2) return 1;
    }
    }
    

    };


  • 0
    M

    @sudeep3
    Thank you! I forget about that version of getline() and you've used it to great effect here.


  • 0
    H

    share my similar solution without without stoior using ' ' to replace'.'; Runtime is 0ms

    int compareVersion(string version1, string version2) {
            istringstream is1(version1);
            istringstream is2(version2);
            int num1 = 0, num2 = 0;
            char c;
            while( bool(is1 >> num1) + bool (is2 >> num2)) {
                if(num1 > num2) return 1;
                if(num1 < num2) return -1;
                is1 >> c; is2 >> c;
                num1 = num2 = 0;
            }
            if(num1 == num2)  return 0;
            return 0;
    

Log in to reply
 

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