🪙
Leetcode
  • Content
  • Algorithms
    • Linear Search
    • Binary Search
    • Counting Sort
    • Merge Sort
    • Insertion Sort
    • Selection Sort
  • Array and String
    • Introduction to Array
      • Introduction to Array
      • Introduction to Dynamic Array
      • Find Pivot Index
      • Largest Number At Least Twice of Others
      • Plus One
    • Introduction to 2D Array
      • Introduction to 2D Array
      • Diagonal Traverse
      • Spiral Matrix
      • Pascal's Triangle
    • Introduction to String
      • Introduction to String
      • Immutable String - Problems & Solutions
      • Add binary
      • Implement strStr()
      • Longest Common Prefix
    • Two-Pointer Technique
      • Two-pointer Technique - Scenario I
      • Reverse String
      • Array Partition I
      • Two Sum II - Input array is sorted
      • Two-pointer Technique - Scenario II
      • Remove Element
      • Max Consecutive Ones
      • Minimum Size Subarray Sum
    • Conclusion
      • Array-related Techniques
      • Rotate Array
      • Pascal's Triangle II
      • Reverse Words in a String
      • Reverse Words in a String III
      • Remove Duplicates from Sorted Array
      • Move Zeroes
  • Linked List
    • Singly Linked List
      • Introduction - Singly Linked List
      • Add Operation - Singly Linked List
      • Delete Operation - Singly Linked List
      • Design Linked List
    • Two Pointer Technique
      • Two-Pointer in Linked List
      • Linked List Cycle
      • Linked List Cycle II
      • Intersection of Two Linked Lists
      • Remove Nth Node From End of List
      • Summary - Two-Pointer in Linked List
  • Problems
    • 1. Two Sum
    • 2. Add Two Numbers
    • 7. Reverse Integer
    • 9. Palindrome Number
    • 11. Container With Most Water
    • 12. Integer to Roman
    • 13. Roman to Integer
    • 14. Longest Common Prefix
    • 15. 3Sum
    • 21. Merge Two Sorted Lists
    • 26. Remove Duplicates from Sorted Array
    • 27. Remove Element
    • 28. Find the Index of the First Occurrence in a String
    • 34. Find First and Last Position of Element in Sorted Array
    • 35. Search Insert Position
    • 43. Multiply Strings
    • 49. Group Anagrams
    • 50. Pow(x, n)
    • 54. Spiral Matrix
    • 58. Length of Last Word
    • 66. Plus One
    • 67. Add Binary
    • 69. Sqrt(x)
    • 73. Set Matrix Zeroes
    • 75. Sort Colors
    • 88. Merge Sorted Array
    • 104. Maximum Depth of Binary Tree
    • 121. Best Time to Buy and Sell Stock
    • 122. Best Time to Buy and Sell Stock II
    • 136. Single Number
    • 146. LRU Cache
    • 189. Rotate Array
    • 206. Reverse Linked List
    • 217. Contains Duplicate
    • 219. Cotains Duplicate II
    • 226. Invert Binary Tree
    • 238. Product of Array Except Self
    • 242. Valid Anagram
    • 268. Missing Number
    • 283. Move Zeroes
    • 350. Intersection of Two Arrays II
    • 383. Ransom Note
    • 389. Find the Difference
    • 412. Fizz Buzz
    • 414. Third Maximum Number
    • 445. Add Two Numbers II
    • 448. Find All Numbers Disappeared in an Array
    • 459. Repeated Substring Pattern
    • 485. Max Consecutive Ones
    • 509. Fibonacci Number
    • 637. Average of Levels in Binary Tree
    • 657. Robot Return to Origin
    • 682. Baseball Game
    • 704. Binary Search
    • 705. Design HashSet
    • 709. To Lower Case
    • 724. Find Pivot Index
    • 876. Middle of the Linked List
    • 896. Monotonic Array
    • 860. Lemonade Change
    • 905. Sort Array By Parity
    • 916. Word Subsets
    • 941. Valid Mountain Array
    • 976. Largest Perimeter Triangle
    • 977. Squares of a Sorted Array
    • 1041. Robot Bounded In Circle
    • 1051. Height Checker
    • 1089. Duplicate Zeros
    • 1232. Check If It Is a Straight Line
    • 1275. Find Winner on a Tic Tac Toe Game
    • 1295. Find Numbers with Even Number of Digits
    • 1299. Replace Elements with Greatest Element on Right Side
    • 1342. Number of Steps to Reduce a Number to Zero
    • 1346. Check If N and Its Double Exist
    • 1476. Subrectangle Queries
    • 1480. Running Sum of 1d Array
    • 1491. Average Salary Excluding the Minimum and Maximum Salary
    • 1502. Can Make Arithmetic Progression From Sequence
    • 1523. Count Odd Numbers in an Interval Range
    • 1572. Matrix Diagonal Sum
    • 1672. Richest Customer Wealth
    • 1768. Merge Strings Alternately
    • 1752. Check if Array Is Sorted and Rotated
    • 1769. Minimum Number of Operations to Move All Balls to Each Box
    • 1790. Check if One String Swap Can Make Strings Equal
    • 1800. Maximum Ascending Subarray Sum
    • 1822. Sign of the Product of an Array
    • 1930. Unique Length-3 Palindromic Subsequences
    • 1991. Find the Middle Index in Array
    • 2185. Counting Words With a Given Prefix
    • 2235. Add Two Integers
    • 2236. Root Equals Sum of Children
    • 2270. Number of Ways to Split Array
    • 2381. Shifting Letters II
    • 2559. Count Vowel Strings in Ranges
    • 2610. Convert an Array Into a 2D Array With Conditions
    • 2657. Find the Prefix Common Array of Two Arrays
    • 3042. Count Prefix and Suffix Pairs I
    • 3105. Longest Strictly Increasing or Strictly Decreasing Subarray
    • 3151. Special Array I
    • 3223. Minimum Length of String After Operations
Powered by GitBook
On this page
  • Example 1
  • Example 2
  • Example 3
  • Constraints
  • Solution
  • Approach Analysis
  • Visualization of Both Approaches
  • Complexity Analysis
  • Why Overflow Prevention Works
  • When to Use Each Approach
  • Common Patterns & Applications
  • Interview Tips

Was this helpful?

Edit on GitHub
  1. Problems

7. Reverse Integer

🟧 Medium

Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-2^31, 2^31 - 1], then return 0.

Assume the environment does not allow you to store 64-bit integers (signed or unsigned).

Example 1

Input: x = 123 Output: 321

Example 2

Input: x = -123 Output: -321

Example 3

Input: x = 120 Output: 21

Constraints

  • -2^31 <= x <= 2^31-1

Solution

My Solution (Basic Reversal)

func reverse(x int) int {
    isNegative := false

    if x < 0 {
        isNegative = true
        x *= -1
    }

    num := 0

    for x != 0 {
        num *= 10
        num += x%10
        x /= 10
    }

    if isNegative {
        num *= -1
    }

    if math.MinInt32 <= num && num <= math.MaxInt32 {
        return num
    }
    
    return 0
}

Optimal Solution (Overflow Prevention)

func reverse(x int) int {
    result := 0
    
    for x != 0 {
        // Get last digit
        pop := x % 10
        x /= 10
        
        // Check overflow before updating result
        if result > math.MaxInt32/10 || (result == math.MaxInt32/10 && pop > 7) {
            return 0
        }
        if result < math.MinInt32/10 || (result == math.MinInt32/10 && pop < -8) {
            return 0
        }
        
        result = result*10 + pop
    }
    
    return result
}

Approach Analysis

This problem combines digit manipulation with careful overflow handling:

  1. Basic Reversal (Your Solution):

    • Handle negative numbers separately

    • Build reversed number digit by digit

    • Check overflow at the end

    • Simple but may have edge cases

  2. Overflow Prevention (Optimal):

    • Check overflow before each operation

    • Handle signs within main logic

    • More robust for edge cases

    • No extra space needed

Visualization of Both Approaches

Basic Reversal Process (Your Solution)

Input: x = 123

Step 1: Extract digits
123 → digit = 3, x = 12
12  → digit = 2, x = 1
1   → digit = 1, x = 0

Step 2: Build result
0    → 0*10 + 3 = 3
3    → 3*10 + 2 = 32
32   → 32*10 + 1 = 321

Overflow Prevention Process

Input: x = 1463847412

Before each step, check:
- Is result > MaxInt32/10? (214748364)
- If result = MaxInt32/10, is digit > 7?

Step 1: 1463847412 → result = 2
Step 2: 146384741  → result = 21
...
Step N: Check prevents overflow

Complexity Analysis

Basic Reversal (Your Solution)

  • Time: O(log₁₀|x|)

    • Process each digit once

    • Number of digits = log₁₀|x|

    • Simple arithmetic operations

  • Space: O(1)

    • Only use few variables

    • Constant extra space

    • No additional data structures

Overflow Prevention (Optimal)

  • Time: O(log₁₀|x|)

    • Same as basic solution

    • Extra overflow checks are O(1)

    • Still process each digit once

  • Space: O(1)

    • Only use result variable

    • Constant extra space

    • No temporary storage needed

Why Overflow Prevention Works

  1. Mathematical Foundation:

    • MaxInt32 = 2147483647

    • MinInt32 = -2147483648

    • Last digits are 7 and -8

    • Division by 10 preserves sign

  2. Early Detection:

    • Check before multiplication

    • Prevents any overflow

    • Handles all edge cases

    • No need for 64-bit integers

When to Use Each Approach

  1. Basic Reversal When:

    • Learning number manipulation

    • Quick implementation needed

    • Input range is known safe

    • Code clarity is priority

  2. Overflow Prevention When:

    • Production environment

    • Unknown input range

    • Performance critical

    • Memory constraints

Common Patterns & Applications

  1. Related Problems:

    • String to Integer (atoi)

    • Palindrome Number

    • Add Two Numbers

    • Multiply Strings

  2. Key Techniques:

    • Digit extraction

    • Overflow checking

    • Sign handling

    • Modular arithmetic

Interview Tips

  1. Solution Highlights:

    • Handle signs properly

    • Check overflow early

    • Process digits efficiently

    • Consider all edge cases

  2. Common Pitfalls:

    • Missing overflow check

    • Wrong sign handling

    • Integer division issues

    • Boundary conditions

  3. Testing Strategy:

    • Positive numbers

    • Negative numbers

    • Zero

    • Maximum integers

    • Minimum integers

  4. Follow-up Questions:

    • Handle decimal points?

    • Different base numbers?

    • Stream of digits?

    • Memory optimization?

Previous2. Add Two NumbersNext9. Palindrome Number

Last updated 5 months ago

Was this helpful?

Leetcode:

link
result