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;
}
相关推荐
牛肉在哪里2 分钟前
ros2 从零开始28 监听广播C++
开发语言·c++·算法·机器人
玖玥拾4 分钟前
C/C++ 数据结构(二)双向链表
c语言·数据结构·c++
乐观勇敢坚强的老彭7 分钟前
GESP一级核心算法:循环与条件判断的结合
java·数据结构·算法
noipp10 分钟前
推荐题目:洛谷 P1737 [NOI2016] 旷野大计算
linux·数据结构·算法
枕星而眠17 分钟前
Linux守护进程完全指南:从原理到实战
linux·运维·服务器·c++·后端
QiLinkOS20 分钟前
极客精神与商业思维的融合实践(2)
c语言·c++·人工智能·算法·开源协议
charlie11451419123 分钟前
现代C++特性指南——constexpr 构造函数与字面类型
开发语言·c++
极客BIM工作室1 小时前
OCCT gp_Trsf 三维变换类深度剖析:经典设计与底层陷阱
c++
code_pgf1 小时前
改进模型架构来减少MLLMs中的幻觉现象
人工智能·深度学习·算法
2301_764441331 小时前
基于AI的本地文件归档智能管理工具梳理
人工智能·python·算法·目标检测·交互