以下是我正在尝试的问题的链接。
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
答案 0 :(得分:3)
您溢出了。 4444371174137455
不适合int
。尝试对uint64_t
和vnum1
使用vnum2