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;
}
相关推荐
.格子衫.34 分钟前
032动态规划之区间DP——算法备赛
算法·动态规划
青 春 记 忆37 分钟前
LeetCode 142. 环形链表 II|Python 解法详解
python·leetcode·链表
莫浅子40 分钟前
day01-USB架构与枚举
c++·单片机·嵌入式驱动
不会代码的小猴1 小时前
7. JSON
开发语言·c++·笔记·qt·算法·json
沫璃染墨2 小时前
《Qt从零入门系列(六):信号与槽进阶——从多种连接方式到Lambda表达式》
开发语言·c++·qt·代码规范·设计规范·qt5
怪奇云呼军2 小时前
知识库也会注入指令?闪电智能VoiceAgent 如何防住 Prompt Injection
人工智能·python·算法·云计算·音视频
阿里云大数据AI技术2 小时前
基于 EMR Serverless Ray 实现 Qwen 模型批量推理实践
人工智能·算法·agent
小小龙学IT3 小时前
ZeroMQ(libzmq)开源消息库深度解析:brokerless 时代的轻量消息内核
c++·开源
Rambo.xia3 小时前
为什么去马赛克算法,决定了ISP的画质上限
算法·接口隔离原则