比较版本号

巴拉斯·卡鲁科拉

以下是我正在尝试的问题的链接。

https://www.interviewbit.com/problems/compare-version-numbers/

我模拟了数组以比较两个版本。但是我在代码中找不到任何错误。

//function that compare string A and string B
//and returns 1 or -1 or 0

int compareVersion(string A, string B) {
    //  vnum1 stores each numeric part of version A
    //  vnum2 stores each numeric part of version B
    int vnum1 = 0, vnum2 = 0;

    //  loop that runs until i and j less than lengths of A and B
    int i=0,j=0;

    while(i<A.length() || j<B.length())
    {
        //  storing numeric part of version A in vnum1

        while (i < A.length() && A[i] != '.')
        {
            vnum1 = vnum1 * 10 + (A[i] - '0');
            i++;
        }

        //  storing numeric part of version B in vnum2
        while (j < B.length() && B[j] != '.')
        {
            vnum2 = vnum2 * 10 + (B[j] - '0');
            j++;
        }

        //returns 1 if version A is greater than version B
        if (vnum1 > vnum2)
            return 1;

        //returns -1 if version B is greater than version A
        if (vnum2 > vnum1)
            return -1;

        //  if both are equal, reset variables and go for next numeric
        // part
        vnum1 = vnum2 = 0;
        i++;
        j++;
    }

    //returns 0 if both are equal
    return 0;
}    

输入:
A =“ 4444371174137455”
B =“ 5.168

预期:1
实际:-1

德米特里

你溢出了。4444371174137455不适合int尝试uint64_t用于vnum1vnum2

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章