这是我目前坚持的家庭作业问题。我必须将整数乘以3,如果有溢出返回最大值(0x7FFFFFFF),则下溢返回最小值(0x80000000)。我使用的是32位数字,仅限于使用运算符: 〜& ^ | +<< >>
我觉得好像我已经解决了它,但当我运行教授测试时,x = 0x7FFFFFFF错误地返回0x7FFFFFFd。可能还有其他测试失败,但这是第一个失败并且没有运行其他测试。
到目前为止,这是我的代码:
int satMul3(int x) {
int threex = x + x + x; //Definition of multiplication 3x = x+x+x
int signx = x >> 31; //Makes bit all same number as MSB (1s = neg 0s = pos)
int sign3 = threex >> 31; //Same as signx but for the result of x*3
int overflow = signx ^ sign3; //Checks if signs are same. 0s if same sign
int tmin = 0x80000000;
int tmax = 0x7FFFFFFF;
int answer = (sign3 & tmin) | (~sign3 & tmax);
//Gets answer for overflow, if sign3 is negative returns Tmin else tmax
return (overflow & answer) | (~overflow & threex); //If overflow is 1,
//signs are the same so return x*3, if overflow is 0, then signs are
//different so return the saturated answer
}
希望这只是一个简单的错误,但如果没有任何建议将不胜感激。