Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #86 Check if integer multiplication will overflow

Write the boolean function multiplyWillOverflow which takes two integers x, y and returns true if (x*y) overflows.

An overflow may reach above the max positive value, or below the min negative value.

public bool multiplyWillOverflow(int x, int y) 
{
	if (x == 0)
		return false;

	if (y > int.MaxValue / x)
		return true;

	if (y < int.MinValue / x)
		return true;

	return false;
}

New implementation...
< >
deleplace