LeetCode //C - 7. Reverse Integer

7. Reverse Integer

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 ] [-2^{31}, 2^{31} - 1] [−231,231−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 -2^{31} <= x <= 2^{31} - 1 −231<=x<=231−1

From: LeetCode

Link: 7. Reverse Integer


Solution:

Ideas:

1. Initialize a result variable (reversed) to zero: This will hold our reversed number.

2. Loop until x is zero:

  • Extract the last digit of x using x % 10.
  • Divide x by 10 to remove the last digit.

3. Overflow/Underflow check:

  • Before appending a digit to reversed, check if appending it would cause the number to overflow or underflow the 32-bit integer limits (INT_MAX and INT_MIN from limits.h).
  • If overflow or underflow is detected, return 0.

4. Construct the reversed number:

Multiply the current reversed by 10 (shift digits left) and add the extracted digit.

Code:
c 复制代码
int reverse(int x) {
    int reversed = 0;

    while (x != 0) {
        int digit = x % 10;  // Get the last digit of x
        x /= 10;             // Remove the last digit from x

        // Check for potential overflow/underflow before actually adding the digit
        if (reversed > INT_MAX / 10 || (reversed == INT_MAX / 10 && digit > 7)) {
            return 0;  // Overflow condition for positive numbers
        }
        if (reversed < INT_MIN / 10 || (reversed == INT_MIN / 10 && digit < -8)) {
            return 0;  // Underflow condition for negative numbers
        }

        reversed = reversed * 10 + digit;  // Append the digit
    }

    return reversed;
}
相关推荐
C语言魔术师19 分钟前
【小游戏篇】三子棋游戏
前端·算法·游戏
自由自在的小Bird19 分钟前
简单排序算法
数据结构·算法·排序算法
刘好念23 分钟前
[OpenGL]实现屏幕空间环境光遮蔽(Screen-Space Ambient Occlusion, SSAO)
c++·计算机图形学·opengl·glsl
C嘎嘎嵌入式开发2 小时前
什么是僵尸进程
服务器·数据库·c++
王老师青少年编程7 小时前
gesp(C++五级)(14)洛谷:B4071:[GESP202412 五级] 武器强化
开发语言·c++·算法·gesp·csp·信奥赛
DogDaoDao7 小时前
leetcode 面试经典 150 题:有效的括号
c++·算法·leetcode·面试··stack·有效的括号
Coovally AI模型快速验证8 小时前
MMYOLO:打破单一模式限制,多模态目标检测的革命性突破!
人工智能·算法·yolo·目标检测·机器学习·计算机视觉·目标跟踪
一只小bit8 小时前
C++之初识模版
开发语言·c++
可为测控8 小时前
图像处理基础(4):高斯滤波器详解
人工智能·算法·计算机视觉
Milk夜雨9 小时前
头歌实训作业 算法设计与分析-贪心算法(第3关:活动安排问题)
算法·贪心算法