Why does signed integer overflow: 2147483647
throw:
runtime error: signed integer overflow: 2147483647 - -100 cannot be represented in type 'int' on this code
temp = abs(nums[i] nums[j] nums[k]-target);
if(temp < abs(minTarget-target)){
minTarget = nums[i] nums[j] nums[k];
}
?
CodePudding user response:
minTarget=nums[i] nums[j] nums[k];
nums[i]
, nums[j]
, nums[k]
maybe below that maximum, but sum is above it.
CodePudding user response:
- -100
cannot be represented in typeint
- -100
is 100 and can be represented as an int
. It is the sum that is a problem.
2147483647 - -100
is mathematically 2147483747
, yet that sum is outside OP's 32-bit int
range of [-2147483648 ... 2147483647]
, hence the run-time error.
Code could use 64-bit math to forestall overflow. Yet the problem may remain if minTarget
must remain int
.
long long temp = llabs(0LL nums[i] nums[j] nums[k] - target);
if(temp < llabs(0LL minTarget - target)){
minTarget = 0LL nums[i] nums[j] nums[k];
}
0LL ...
insures at least 64-bit math in the addition/subtraction.