runtime error: signed integer overflow: 998765432 * 10 cannot be represented in type ‘int’ [solution.c]
今天在力扣中编写回文数算法的时候,发现就是运行失败,提示为:
Char 26: runtime error: signed integer overflow: 998765432 * 10 cannot be represented in type 'int' [solution.c]
运行时错误:有符号整数溢出:998765432*10不能在类型“int”[solution.c]中表示。
于是我把int改为了long long类型,运行成功。我就很奇怪,这为什么能溢出。之后发现是力扣的系统会用各种各样的数据去测试你的代码,它用了一个很大的数去测试代码,所以就发生了溢出。
改之前:
bool isPalindrome(int x){
int t,asist=x;
int reverse=0;
if(asist<0) return false;
while(asist){
t=asist%10;
reverse=t+reverse*10;
asist=asist/10;
}
if(x!=reverse) return false;
return true;
}
因为是reverse溢出,所以把reverse改为了long long型:
long long reverse=0;
结果正确。
之后上网查了int和long long之间的区别。得到:能用int就尽量用int,long long虽然能增大数据范围,但是也会增加代码运行时间。