Share my cpp version by convert version number to int


  • 0
    B
    class Solution {
    public:
    int compareVersion(string version1, string version2) {
        // index for version1 and version2
        int i = 0, j = 0;
        int len1 = version1.length(), len2 = version2.length();
        string str1, str2;
        while (i < len1 || j < len2) {
    	while (version1[i] != '.' && i < len1)
    	    str1 += version1[i++];
    	while (version2[j] != '.' && j < len2)
    	    str2 += version2[j++];
    	
    	int num1 = atoi(str1.c_str());
    	int num2 = atoi(str2.c_str());
    	if (num1 > num2)
    	    return 1;
    	if (num1 < num2)
    	    return -1;
    	
    	i++;
    	j++;
    	str1 = "";
    	str2 = "";
        }
        return 0;
    }
    };

Log in to reply
 

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