I want to handle the special case where multiplying two numbers together causes an overflow. The code looks something like this:
int a = 20;
long b = 30;
// if a or b are big enough, this result will silently overflow
long c = a * b;
That's a simplified version. In the real program a
and b
are sourced elsewhere at runtime. What I want to achieve is something like this:
long c;
if (a * b will overflow) {
c = Long.MAX_VALUE;
} else {
c = a * b;
}
How do you suggest I best code this?
Update: a
and b
are always non-negative in my scenario.
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…