C++ 8-line concise solution using stringstream and handling overflow (detailed explanation)


  • 0

    Based on some of OJ's test cases, I think OJ should have explicitly made the following 2 assumptions:

    • The version string might contain arbitrary occurrence of '.' including no '.'.
    • A sub-version string could contain leading 0's which must be ignored during comparison.

    Then the idea will be straightforward to simply use delimiter '.' to split version string into sub-version strings, trim all potential leading 0's and compare version numbers. Note that the version number represented as string could overflow if converted to int, so we should check two digit strings by comparing length first and then comparing by strings.

        int compareVersion(string v1, string v2) {
        	stringstream ss1(v1), ss2(v2);
        	while (ss1 || ss2) {
        	  auto s1(getVersion(ss1)), s2(getVersion(ss2)); int comp;
        	  if ((comp = s1.length() - s2.length()) || (comp = s1.compare(s2))) return comp > 0 ? 1 : -1;
        	}
        	return 0;
        }
        string getVersion(stringstream& ss) { // get current version string without leading 0's
          string s; getline(ss, s, '.'); size_t p = s.find_first_not_of('0');
          return p == string::npos? "" : s.substr(p);
        }
    

Log in to reply
 

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