THN Interview Prep

7. Reverse Integer

At a Glance

  • Topic: math-geometry
  • Pattern: Math + overflow guard (canonical home for this problem)
  • Difficulty: Medium
  • Companies: Amazon, Apple, Bloomberg, Adobe, Microsoft
  • Frequency: High
  • LeetCode: 7

Problem (one-liner)

Reverse the decimal digits of a signed 32-bit integer; return 0 if the reversed value is outside the signed 32-bit range [-2³¹, 2³¹-1].

Recognition Cues

  • "Reverse integer"
  • Explicit overflow handling to zero
  • Digit pop/push pattern

Diagram

At-a-glance flow (replace with problem-specific Mermaid as you refine this note). camelCase node IDs; no spaces in IDs.

Loading diagram…

Approaches

  • Brute force — string reverse — needs parse overflow check anyway.
  • Optimal — iterative pop last digit, push to result — O(log |x|) time / O(1) space — check overflow before multiplying by 10.

Optimal Solution

Go

package main

const int32Max = 2147483647
const int32Min = -2147483648

func reverse(value int) int {
	result := 0
	for value != 0 {
		digit := value % 10
		value /= 10
		if result > int32Max/10 || (result == int32Max/10 && digit > 7) {
			return 0
		}
		if result < int32Min/10 || (result == int32Min/10 && digit < -8) {
			return 0
		}
		result = result*10 + digit
	}
	return result
}

JavaScript

const INT32_MAX = 2147483647;
const INT32_MIN = -2147483648;

function reverse(value) {
	let result = 0;
	while (value !== 0) {
		const digit = value % 10;
		value = Math.trunc(value / 10);
		if (
			result > Math.trunc(INT32_MAX / 10) ||
			(result === Math.trunc(INT32_MAX / 10) && digit > 7)
		) {
			return 0;
		}
		if (
			result < Math.trunc(INT32_MIN / 10) ||
			(result === Math.trunc(INT32_MIN / 10) && digit < -8)
		) {
			return 0;
		}
		result = result * 10 + digit;
	}
	return result;
}

Walkthrough

Input: value = 1534236469 (overflow case)

Each step checks whether result*10 + digit would exceed bounds before committing.

Edge Cases

  • Trailing zeros become leading zeros after reverse — dropped by integer semantics
  • value = 0
  • Min/max boundary reversals

Pitfalls

  • Using 64-bit accumulator without clamp — problem wants 0 on overflow
  • JS: use Math.trunc for division toward zero

Similar Problems

Variants

  • Reverse in arbitrary base.
  • Return clamped value instead of zero (different spec).

Mind-Map Tags

#overflow #digit-manipulation #math #int32-bounds

Last updated on

Spotted something unclear or wrong on this page?

On this page