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;
}
相关推荐
ゞ 正在缓冲99%…1 分钟前
leetcode76.最小覆盖子串
java·算法·leetcode·字符串·双指针·滑动窗口
xuanjiong2 分钟前
纯个人整理,蓝桥杯使用的算法模板day2(0-1背包问题),手打个人理解注释,超全面,且均已验证成功(附带详细手写“模拟流程图”,全网首个
算法·蓝桥杯·动态规划
Zhichao_9719 分钟前
【UE5 C++课程系列笔记】33——商业化Json读写
c++·ue5
惊鸿.Jh21 分钟前
【滑动窗口】3254. 长度为 K 的子数组的能量值 I
数据结构·算法·leetcode
明灯L21 分钟前
《函数基础与内存机制深度剖析:从 return 语句到各类经典编程题详解》
经验分享·python·算法·链表·经典例题
碳基学AI27 分钟前
哈尔滨工业大学DeepSeek公开课:探索大模型原理、技术与应用从GPT到DeepSeek|附视频与讲义免费下载方法
大数据·人工智能·python·gpt·算法·语言模型·集成学习
补三补四31 分钟前
机器学习-聚类分析算法
人工智能·深度学习·算法·机器学习
独好紫罗兰41 分钟前
洛谷题单3-P5718 【深基4.例2】找最小值-python-流程图重构
开发语言·python·算法
云边有个稻草人1 小时前
【C++】第八节—string类(上)——详解+代码示例
开发语言·c++·迭代器·string类·语法糖auto和范围for·string类的常用接口·operator[]
正脉科工 CAE仿真1 小时前
基于ANSYS 概率设计和APDL编程的结构可靠性设计分析
人工智能·python·算法