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;
}
相关推荐
fqbqrr3 分钟前
2601C++,导出控制
c++
陌路2014 分钟前
日志系统7--异步日志的实现
c++
老鼠只爱大米18 分钟前
LeetCode算法题详解 438:找到字符串中所有字母异位词
算法·leetcode·双指针·字符串匹配·字母异位词·滑动窗口算法
程序员Jared26 分钟前
C++11—this_thread
c++·this_thread
地平线开发者29 分钟前
征程 6 | 平台 QAT 精度一致性问题分析流程
算法·自动驾驶
mjhcsp32 分钟前
C++ Manacher 算法:原理、实现与应用全解析
java·c++·算法·manacher 算法
AlenTech1 小时前
198. 打家劫舍 - 力扣(LeetCode)
算法·leetcode·职场和发展
Z1Jxxx1 小时前
0和1的个数
数据结构·c++·算法
ldccorpora1 小时前
Chinese News Translation Text Part 1数据集介绍,官网编号LDC2005T06
数据结构·人工智能·python·算法·语音识别
重生之后端学习1 小时前
21. 合并两个有序链表
java·算法·leetcode·链表·职场和发展