use checkedint to check overflow

Refactor to simplify the logic.