gpt4 book ai didi

c++ - 比较版本号

转载 作者:搜寻专家 更新时间:2023-10-31 01:24:39 24 4
gpt4 key购买 nike

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

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。尝试对 vnum1vnum2

使用 uint64_t

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com