Medium Problems

7. Reverse Integer

Solutions

Pop and Push digits & Check before Overflow

// pop operation
pop = x % 10 // use '%' modulus operation
x /= 10 // divided by 10
 
// push operation
temp = rev * 10 + pop
rev = temp

However, the statement temp=rev.10+poptemp = rev.10 + pop can cause overflow. How can we check overflow beforehand? Assuming rev is positive, then:

  1. If temp=rev.10+poptemp = rev.10 + pop causes overflow, then it must be that rev>=INTMAX10rev >= {\frac {INTMAX}{10}}
  2. If rev>INTMAX10rev > {\frac {INTMAX}{10}}, then temp=rev.10+poptemp = rev.10 + pop is guaranteed to overflow.
  3. If rev=INTMAX10rev = {\frac {INTMAX}{10}}, then temp=rev.10+poptemp = rev.10 + pop will overflow if and only if pop>7pop > 7

Implementation

function reverse(x: number): number {
  const MIN_INT = -2147483648
  const MAX_INT = 2147483647
 
  let rev = 0;
  let pop;
  while (x !== 0) {
      // pop operation
      pop = x % 10;
      x  = (x - pop) / 10; // trip off the last digit before dividing by 10
 
      // check overflow
      if (rev > MAX_INT / 10 || (rev === MAX_INT / 10 && pop > 7)) {
          return 0;
      }
      if (rev < MIN_INT / 10 || (rev === MIN_INT / 10 && pop < -8)) {
          return 0;
      }
 
      // push operation
      rev = rev * 10 + pop // this statement can cause overflow
  }
  return rev;
};
Last Update: 11:43 - 16 April 2024
Math

On this page