Zum Hauptinhalt springen
tsecurity.de LIVE
Echtzeit-Radar & Feeds
Alle RSS Feeds
👥 Community & Social
Sichere ProgrammierungThe Indie Dev Visibility Playbook: From Zero Users to Your First 100(21.09.2026 um 00:08 Uhr)
Sichere ProgrammierungBase, Chat and Reasoning Models: How Are They Different?(21.09.2026 um 00:09 Uhr)
Sichere ProgrammierungHexfield Deck is for Kanban lovers and Markdown believers(21.09.2026 um 00:20 Uhr)
Sichere ProgrammierungPermissions and Authorisation: A Practical Playbook(21.09.2026 um 00:21 Uhr)
Linux Tipps & Hardeningfilet | Terminal File Manager(20.09.2026 um 21:03 Uhr)
Linux Tipps & HardeningLooking for feedback on my Linux Distro(20.09.2026 um 21:03 Uhr)
Sichere ProgrammierungThe Indie Dev Visibility Playbook: From Zero Users to Your First 100(21.09.2026 um 00:08 Uhr)
Sichere ProgrammierungBase, Chat and Reasoning Models: How Are They Different?(21.09.2026 um 00:09 Uhr)
Sichere ProgrammierungHexfield Deck is for Kanban lovers and Markdown believers(21.09.2026 um 00:20 Uhr)
Sichere ProgrammierungPermissions and Authorisation: A Practical Playbook(21.09.2026 um 00:21 Uhr)
Linux Tipps & Hardeningfilet | Terminal File Manager(20.09.2026 um 21:03 Uhr)
Linux Tipps & HardeningLooking for feedback on my Linux Distro(20.09.2026 um 21:03 Uhr)
Intelligence View
⚡ tsecurity.de Intelligence

LeetCode Solution: 7. Reverse Integer

Reagiere als Erste:r — dein Feedback zählt!

🚀 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;
    }
};

⏱️ 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

Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten LeetCode Solution: 7. Reverse Integer

Thematisch verwandte Begriffe: LeetCode, Solution, Reverse, Integer · 6 Treffer

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Zum Aktualisieren ziehen
ZERO-DAY CVE-2026-94084 | Suricata before 8.0.7 has an Http2ThreadMultiBuf use-after-free when a t…
Advisory →
TTS Reader • tsecurity.de Voice
tsecurity.de Icon
tsecurity.de App
Offline-Lesen, Eilmeldungen & 0ms Ladezeit

Installiere tsecurity.de direkt auf deinen Home-Bildschirm für das ultimative Vollbild-Magazinerlebnis ohne Browser-Leisten.

Nächster Beitrag
Themen-Radar & Intelligence Matrix
Echtzeit-Taxonomie nach Angriffsvektoren & Plattformen

tsecurity.de Live Threat Radar

🔴 LIVE RADAR
MONITORING
AKTIV
CVE-DATENBANK
LIVE
🔍
Community Radar & Live Chat
Sentinel Bot online • Live-Stream
Dein Cluster: Security Explorer
Match:
lädt…
Verbindung zum Community-Stream wird aufgebaut...
Bearbeitungsmodus — Senden überschreibt deine Nachricht
Community-Puls — was gerade passiert
lädt…
Aktivitäten deiner Analysten
lädt…
Neues Thema oder Eilmeldung einreichen

Reiche interessante Links, Zero-Days oder Debatten ein. Die Community entscheidet per Upvote über die Veröffentlichung.

Heiß diskutierte Einreichungen
🔖 Gespeicherte Artikel
📂 Keine gespeicherten Artikel vorhanden.
Zurück Ziehen Vor
Links: vorheriger Artikel Rechts: nächster Artikel unten: schließen
News NIS-2 Frühwarnung Tier-1 Intel ⏱️ 3 Min vor 10 Min
Artikeldaten werden geladen...

Zurück: vorheriger Vor: nächster
↗ Original-Quelle
Social Reaktionen Deine Reaktion zählt
Einstufung & Relevanz-Poll 0 Stimmen
In sozialen Netzwerken teilen 1-Klick