Reverse Integer & Overflow Handling

Reverse Integer

Reverse Integer: pop and push

  • Pop: take the last digit out by using x % 10
  • Push:push this digit back by rev * 10 + digit

Overflow Handling

  • Make sure the result is not larger than INT_MAX or smaller than INT_MIN
  • Compare them BEFORE push back digits
if (rev > INT_MAX / 10 || (rev == INT_MAX / 10 && digit > 7 ))

or

if (rev < INT_MIN / 10 || (rev == INT_MIN / 10 && digit < -8))

Leave a Reply

Discover more from Daily Learning

Subscribe now to keep reading and get access to the full archive.

Continue reading