Hi all I was wondering if there is a way to implement this method without casting to a wider data type (e.g. long, double, etc)?
CanTimes(int a, int b){
returns true if a * b is within the range of -2^31 to 2^31-1, else false;
}
For example, we could implement one for the method CanAdd
(without casts) as such:
public static boolean CanPlus(int a, int b) {
if (b >= 0) {
return a <= Integer.MAX_VALUE - b
} else {
return a >= Integer.MIN_VALUE - b
}
}
Implementation language is Java, though of course this is more of a language-agnostic problem.
I was thinking if there's some logic we can employ to decide if a * b fits the range of an integer without casting it to a wider data type?
Solution ! based on Strelok's comment:
public static boolean CanTimes(int a, int b) {
if (a == 0 || b == 0) {
return true;
}
if (a > 0) {
if (b > 0) {
return a <= Integer.MAX_VALUE / b;
} else {
return a <= Integer.MIN_VALUE / b;
}
} else {
if (b > 0) {
return b <= Integer.MIN_VALUE / a;
} else {
return a <= -Integer.MAX_VALUE / b;
}
}
}