मुख्य कंटेंट तक स्किप करें

Reverse Integer

KANISHKA GUPTA
EditReport

Problem Statement

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.

Video Explanation

Approach

To reverse an integer, we can repeatedly extract the last digit using the modulo operator (% 10) and append it to our reversed number by multiplying the current reversed number by 10 and adding the extracted digit.

Steps:

  1. Initialize:

    • Create a variable reversed_num and set it to 0.
    • Keep track of the sign of x.
  2. Iterate:

    • While x is not zero:
      • Extract the last digit: digit = abs(x) % 10
      • Update x: x = int(x / 10) (truncating towards zero)
      • Append the digit: reversed_num = (reversed_num * 10) + digit
  3. Check Bounds:

    • If reversed_num goes beyond the 32-bit signed integer range [-2^31, 2^31 - 1], return 0.
  4. Return:

    • Restore the sign and return reversed_num.

Solutions

#include <climits>

class Solution {
public:
int reverse(int x) {
int reversed_num = 0;
while (x != 0) {
int digit = x % 10;
x /= 10;
if (reversed_num > INT_MAX / 10 || (reversed_num == INT_MAX / 10 && digit > 7)) return 0;
if (reversed_num < INT_MIN / 10 || (reversed_num == INT_MIN / 10 && digit < -8)) return 0;
reversed_num = reversed_num * 10 + digit;
}
return reversed_num;
}
};
Track Your Progress

Done with this topic? Mark it as complete to track your progress.

💬 Discuss this page

Have a question or spot something confusing in "Reverse Integer"? Ask below — it's backed by GitHub Discussions, so maintainers get notified like any other GitHub activity.