c++ - 比较版本号

标签 c++

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

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

关于c++ - 比较版本号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57971290/

相关文章:

c++ - 由在 DTor 之前删除的静态对象创建的线程?

c++ - 为什么概念不能传递给模板元函数?

c++ - 在 C++ 中实现简单的服务器/客户端概念

c++ - 使用带有 operator== 的 std::find 时出错

c++ - SChannel/SSL 实现?

c++ - 将 std::bind 的结果传递给 std::function "overloads"

c++ - C++中类数据成员的初始化

C++将所有函数从共享库复制到可执行文件

c++ - 使用 argv 读取图像

c++ - 更改凹槽背景时隐藏 QSlider handle