惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
SegmentFault 最新的问题
J
Java Code Geeks
V
V2EX
Blog — PlanetScale
Blog — PlanetScale
博客园 - 司徒正美
Hugging Face - Blog
Hugging Face - Blog
F
Fortinet All Blogs
aimingoo的专栏
aimingoo的专栏
B
Blog
A
About on SuperTechFans
有赞技术团队
有赞技术团队
月光博客
月光博客
Microsoft Azure Blog
Microsoft Azure Blog
阮一峰的网络日志
阮一峰的网络日志
腾讯CDC
美团技术团队
大猫的无限游戏
大猫的无限游戏
爱范儿
爱范儿
N
Netflix TechBlog - Medium
C
Check Point Blog
Recent Announcements
Recent Announcements
博客园 - Franky
博客园 - 叶小钗
T
Tailwind CSS Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
LeetCode Solution: 7. Reverse Integer
Vansh Aggarw · 2026-04-24 · via DEV Community

Vansh Aggarwal

🚀 Master LeetCode 7: Reversing Integers Without Breaking the Bank (or Your Code!)

Hey LeetCoders and aspiring developers! 👋 Vansh2710 here, your friendly neighborhood competitive programmer and technical writer. Today, we're diving into a classic LeetCode problem that might seem simple on the surface but hides a crucial detail that trips up many beginners (and even some seasoned folks!): Reverse Integer (Problem 7).

It's a fantastic problem to learn about integer manipulation and, more importantly, how to handle those pesky overflow scenarios. Let's conquer it together!

📖 Problem Explained: The Digit Dilemma

You're given a signed 32-bit integer x. Your task is to return x with its digits reversed. Sounds easy, right?

Here's the catch: If reversing x causes its value to go outside the signed 32-bit integer range (which is [-2^31, 2^31 - 1]), you must return 0. Oh, and you can't use 64-bit integers. This last constraint is key!

Let's look at some examples to get a feel for it:

  • Example 1:

    • Input: x = 123
    • Output: 321 (Simple positive reversal)
  • Example 2:

    • Input: x = -123
    • Output: -321 (Negative numbers reverse similarly, keeping the sign)
  • Example 3:

    • Input: x = 120
    • Output: 21 (Trailing zeros become leading zeros and get dropped)

The core idea seems straightforward, but the "overflow" part is where the real challenge lies!

✨ Intuition: Building Backwards, Digit by Digit

Imagine you have the number 123. How would you "reverse" it manually?

  1. You'd grab the 3.
  2. Then the 2.
  3. Then the 1.

And then you'd put them together as 321.

How can we do this programmatically?

  • Getting the last digit: The modulo operator (%) is our best friend! 123 % 10 gives us 3.
  • Removing the last digit: Integer division (/) comes to the rescue! 123 / 10 gives us 12.
  • Building the reversed number: Let's say we have a reversed_num variable, initially 0.
    • When we get 3: reversed_num = 0 * 10 + 3 = 3.
    • When we get 2: reversed_num = 3 * 10 + 2 = 32.
    • When we get 1: reversed_num = 32 * 10 + 1 = 321.

This "extract-and-build" loop forms the heart of our solution. But wait! What if x is 2147483647 (which is INT_MAX)? Reversing it would give 7463847412, which is much larger than INT_MAX. This is where our overflow check becomes absolutely vital! We need to detect this before it happens.

🧠 Our Step-by-Step Approach

Let's break down the logic into clear, manageable steps:

  1. Initialize reversed_num: We'll need a variable, let's call it reversed_num, initialized to 0. This will store our result as we build it.
  2. Loop While x Has Digits: We'll use a while loop that continues as long as x is not 0. Each iteration will process one digit.
  3. Extract the Last Digit: Inside the loop, get the last digit of x using int digit = x % 10;.
  4. 🚨 CRITICAL OVERFLOW CHECK 🚨: This is the most important part! Before we actually update reversed_num with the new digit, we need to check if doing so would cause an overflow (i.e., exceed INT_MAX or go below INT_MIN).
    • How to check?
      • If reversed_num is already greater than INT_MAX / 10, then multiplying reversed_num by 10 will definitely overflow.
      • If reversed_num is exactly INT_MAX / 10, then adding a digit greater than 7 (since INT_MAX is 2,147,483,647 and 7 is its last digit) will cause an overflow.
      • Similar logic applies for INT_MIN: if reversed_num < INT_MIN / 10 or (reversed_num == INT_MIN / 10 and digit < -8), it will underflow.
    • If any overflow/underflow is detected, immediately return 0 as per the problem statement.
  5. Build reversed_num: If no overflow is detected, safely update reversed_num: reversed_num = reversed_num * 10 + digit;.
  6. Shrink x: Remove the last digit from x by integer division: x /= 10;.
  7. Return Result: Once the loop finishes (meaning x is 0 and all digits have been processed), return the final reversed_num.

✍️ The Code (C++)

Here's the C++ implementation incorporating the logic we just discussed:

#include <limits.h> // Required for INT_MAX and INT_MIN

class Solution {
public:
    int reverse(int x) {
        int reversed_num = 0; // This will store our reversed integer

        // Loop until x becomes 0 (all digits processed)
        while (x != 0) {
            // Extract the last digit of x
            int digit = x % 10;

            // --- CRITICAL OVERFLOW CHECK ---
            // This check must happen BEFORE we update `reversed_num`.
            // We're essentially asking: "If I multiply `reversed_num` by 10
            // and add `digit`, will it go out of bounds?"

            // Positive overflow check:
            // 1. If `reversed_num` is already greater than `INT_MAX / 10`,
            //    multiplying by 10 will *definitely* overflow.
            // 2. If `reversed_num` is exactly `INT_MAX / 10`,
            //    adding `digit` will cause overflow IF `digit` is greater than 7.
            //    (Because INT_MAX = 2,147,483,647, so the last digit is 7).
            if (reversed_num > INT_MAX / 10 || (reversed_num == INT_MAX / 10 && digit > 7)) {
                return 0; // Overflow detected, return 0
            }

            // Negative overflow check:
            // 1. If `reversed_num` is already less than `INT_MIN / 10`,
            //    multiplying by 10 will *definitely* underflow.
            // 2. If `reversed_num` is exactly `INT_MIN / 10`,
            //    adding `digit` will cause underflow IF `digit` is less than -8.
            //    (Because INT_MIN = -2,147,483,648, so the last digit is -8).
            if (reversed_num < INT_MIN / 10 || (reversed_num == INT_MIN / 10 && digit < -8)) {
                return 0; // Underflow detected, return 0
            }

            // If no overflow, safely build the reversed number
            reversed_num = reversed_num * 10 + digit;

            // Remove the last digit from x
            x /= 10;
        }

        // All digits processed, return the final reversed number
        return reversed_num;
    }
};

Enter fullscreen mode Exit fullscreen mode

⏱️ Time & Space Complexity Analysis

Time Complexity: O(log |x|)

Why O(log |x|)?
Because in each iteration of our while loop, we're effectively removing one digit from x (by dividing x by 10). The number of digits in an integer x is proportional to log10 |x|. For a 32-bit integer, the maximum number of digits is around 10 (since 2^31 - 1 is roughly 2 * 10^9). So, even for the largest possible x, the loop runs a very small, constant number of times. It's incredibly efficient!

Space Complexity: O(1)

We are only using a few extra variables (reversed_num, digit, etc.) whose memory usage does not change with the input size x. Therefore, the space complexity is constant.

🎯 Key Takeaways

  • Digit Manipulation Power Duo: Remember num % 10 to get the last digit and num / 10 to remove it. They are fundamental for many integer-based problems.
  • The Dreaded Overflow: Always be mindful of integer limits, especially in problems specifying fixed-size types (like 32-bit integers).
  • Proactive Overflow Checks: The golden rule is to check for potential overflow before performing the operation that might cause it. Don't wait for your program to crash!
  • Building Numbers: The pattern result = result * 10 + digit is a common and powerful technique for constructing numbers from their digits.
  • Edge Cases Matter: Think about negative numbers and numbers ending in zero (like 120 becoming 21). Our solution handles these gracefully!

This problem is a fantastic way to solidify your understanding of basic arithmetic operations and introduce you to the critical concept of overflow handling in programming. Keep practicing, and you'll be a LeetCode master in no time!


Author: Vansh2710

Published: 2026-04-24 00:33:03