LeetCode Algorithm #7 Reverse Integer

本文介绍了解决LeetCode上的整数反转问题的几种方法,包括通过循环取余实现数字翻转,利用字符串操作进行反向取值,并讨论了如何处理32位整数的溢出情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

LeetCode Algorithm #7 Reverse Integer

题目内容

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

Have you thought about this?

Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

If the integer’s last digit is 0, what should the output be? ie, cases such as 10, 100.

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.

解题

解题的过程是多种多样的,但是不外乎分为两个过程,一个是将输入翻转存在long long类型中,一个是根据这个long long数值判断是否溢出。

输入翻转

循环取余

循环取余即将输入的数字每次余10取出个位数,将这个个位数追加到翻转后数字的末尾,再将输入数字除10,直到输入数字变为0。

最朴素的方法就是使用基本运算符

long long y = 0;
while(x != 0) {
    y = 10*y + x%10;
    x /= 10;
}

另一种是使用<cstdlib>中的div_t div(int numer, int denom)函数,可以在返回的div_t变量中取到商和余数。

long long revn = 0;
div_t r;
while(x != 0) {
    r = div(x, 10);
    revn = revn*10 + r.rem;
    x = r.quot;
}
字符串反取

这种方法主要利用的是字符串,将输入转换为字符串,再从最后一位开始取将其转换为数字。不过要多加一个正负的判断。

bool negative = false;
if(x < 0) {
    negative = true;
    x = -x;
}
char buf[16];
sprintf(buf, "%d", x);
int length = strlen(buf);
long long result = 0;
for(int i = length-1; i >= 0; --i)
    result = result*10 + (buf[i]-'0');

溢出判断

一种是使用强制转换为int再转回long long,与原来的值做比较是否有变化。

if((long long)((int)result) != result)
    return 0;

另一种是直接和INT_MAX比较,看是否超出了int类型的上界。

if(abs(revn) > INT_MAX) {
    revn = 0;
}

运行时间

结果是使用强制转换要比取绝对值判断大小要快得多,而翻转这一块则相差得不多。不过个人水平有限,这些方法在所有submissions中都不算快。并且相同的代码运行结果也不尽相同。

贴一个我的submissions中最快的12ms的代码

class Solution {
public:
    int reverse(int x) {
        bool negative = false;
        if(x < 0) {
            negative = true;
            x = -x;
        }
        char buf[16];
        sprintf(buf, "%d", x);
        int length = strlen(buf);
        long long result = 0;
        for(int i = length-1; i >= 0; --i)
            result = result*10 + (buf[i]-'0');
        if((long long)((int)result) != result)
            return 0;
        return negative ? -(int)result : (int)result;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值