Simple C++ 2 ms with istringstream


  • 0
    int compareVersion(string version1, string version2) {
        int v1 = 0;
        int v2 = 0;
        int value = 0;
    
        for( size_t i = 0; i < version1.size(); i++ ) if ( version1[i] == '.' ) version1[i] = ' ';
        for( size_t i = 0; i < version2.size(); i++ ) if ( version2[i] == '.' ) version2[i] = ' ';
    
        istringstream ss1( version1 );
        istringstream ss2( version2 );
    
        while( ss1.rdbuf()->in_avail() > 0 || ss2.rdbuf()->in_avail() > 0 )
        {
            ss1 >> v1;
            ss2 >> v2;
    
            if( v1 > v2 ) return 1;
            else if ( v1 < v2 ) return -1;
    
            v1 = 0;
            v2 = 0;
        }
    
        return 0;
    }

Log in to reply
 

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