我正在解决LeetCode problem:7.反向整数,为了测试目的,我打印了一些值(long long x2和long long x3)。在这里,如果xRough或xRough为负值,则将x和xRough的值分配给x和x3,否则将确定一个未定义的值。但是,LeetCode编译器将xRough的值分配给x2和x3,即使x是正的(而不是分配未定义的值)。我在不同的编译器上测试了这段代码,当x2和x3为阳性时,它们给出了未定义的值。但是LeetCode编译器给出了错误的结果。
这难道不是LeetCode编译器的错误或奇怪行为吗?还是我在这里遗漏了一些要点?
class Solution {
public:
int reverse(int x) {
long long x2, x3;
long long xRough = (long long) x;
if (xRough < 0){
x2 = x3 = (-1) * xRough;
}
cout<<x2<<" "<<x3<<" "<<xRough<<endl;
return 0;
}
};我还让接受了带有这种奇怪的编译器行为的。已接受的守则是:
class Solution {
public:
int reverse(int x) {
long long flag = 0, y, x2, x3, xRough = (long long) x;
long long theNum = 0, i = 1;
if (xRough < 0)
x2 = x3 = std::abs(xRough);
while (1) {
x2 = x2 / 10;
i = i * 10;
if (x2 == 0)
break;
}
i = i / 10;
while (1) {
y = x3 % 10;
x3 = x3 / 10;
theNum = theNum + y * i;
i = i / 10;
if (x3 == 0)
break;
}
if (x < 0) {
if (theNum > std::pow(2, 31))
return 0;
else
return (-1) * theNum;
} else {
if (theNum > (std::pow(2, 31) - 1))
return 0;
else
return theNum;
}
}
};发布于 2022-01-24 12:48:51
在你的职能中:
class Solution {
public:
int reverse(int x) {
long long x2, x3;
long long xRough = (long long) x;
if (xRough < 0){
x2 = x3 = (-1) * xRough;
}
cout<<x2<<" "<<x3<<" "<<xRough<<endl;
return 0;
}
};有两种情况必须加以区分。xRough < 0要么是true,要么是false。
当它是true时,x2将得到一个被分配的值,并且一切都如您所期望的那样工作。
当它是false时,代码尝试打印x2和x3的值,但是它们没有初始化。它们具有不确定的值。如果不调用未定义的beahvior,就不能使用不确定的值进行任何操作。
函数定义输出的唯一方法是当xRough < 0是true时。当它是假的,输出可以是任何东西。因此,编译器允许完全忽略xRough < 0是false的情况。这就是编译器构建的目的,这就是为什么他们擅长优化代码,他们可以消除代码中从未使用的路径(也可能永远不会使用,因为结果是未定义的)。
https://stackoverflow.com/questions/70833795
复制相似问题