Reputation: 99
I am working on a problem from LeetCode (not an interview question just practicing) that asks the following:
Given a sorted integer array nums, where the range of elements are in the inclusive range [lower, upper], return its missing ranges.
The code that I came up with fails for inputs where the nums
array is [-2147483648,2147483647]
and lower/upper
are -2147483648/2147483647
respectively. The part of my code that actually answers the question is:
if (nums[0]-lower > 1) {
String range = lower + "->" + (nums[0]-1);
ans.add(range);
}
else if (nums[0]-lower == 1) {
String range = new Integer(lower).toString();
ans.add(range);
}
for (int i = 1; i < nums.length; i++) {
if (nums[i] - nums[i-1] > 2) {
String range = nums[i-1]+1 + "->" + (nums[i]-1);
ans.add(range);
}
else if (nums[i] - nums[i-1] == 2) {
String range = new Integer(nums[i]-1).toString();
ans.add(range);
}
}
I was wondering how best to handle this edge case, not just for this question but generally. Do I just add extra if-statements
to my code to specifically handle these two numbers (or if addition/subtraction of numbers causes the int value to overflow) or is there a more elegant way to handle this?
Upvotes: 2
Views: 1319
Reputation: 31279
The maximum value of an int
is 231-1 which is 2147483647, but the difference between that number and any negative number is larger than that number itself.
So all your subtraction expressions like nums[0]-lower
overflow with [-2147483648,2147483647]
(or [-1,2147483647]
).
You can check it with this:
System.out.println(2147483647 - -1);
This prints out -2147483648
even though you would expect it to be 2147483648
.
One easy fix is to do the calculations as a 64-bit long
. Change all your subtractions like below to cast the expression to long
.
if (nums[0] - (long)lower > 1) {
Take the above example and change it to:
System.out.println(2147483647 - (long) -1);
This will correctly print 2147483648
.
Upvotes: 5