刷Leetcode时错误:
class Solution {
public:
int mySqrt(int x) {
int index=1;
long long square=1;
while(square<=x){
if(square==x)
return index;
index++;
square=index*index;
}
return index-1;
}
};
两个int*int型变量相乘结果显示溢出,虽然square已经声明为long long,但是 int*int的结果先放在int变量中,与前面的变量类型无关。
解决方法:
把index声明为long或者long long类型。
在LeetCode中遇到整数平方根计算导致的溢出错误,文章解释了问题原因及解决方法。通过将变量`index`声明为`long`或`long long`类型,避免了`int`乘`int`导致的中间结果溢出,从而正确计算平方根。
7788

被折叠的 条评论
为什么被折叠?



