7. Reverse Integer

本文介绍了一种有效的整数反转算法,该算法通过模除10的方法找到整数的每一位并将其反转,同时处理符号和溢出的问题。文章还讨论了在特定情况下的输出规则,并提供了一个实现此功能的C++代码示例。

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

问题描述:

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.

https://leetcode.com/problems/reverse-integer/description/


思路分析:将一个int值的低位与高位互换,并保持原来的符号不变。要注意的是int的范围为-2147483648~2147483647,所以有些int值反转之后会出现overflow,此时应当作出相应的异常处理。基本思路就是使用模除10来不断找到最小位,然后加不断加起来。为防止溢出,是存放在一个long变量中的,进行判断之后再返回。


代码:

class Solution {
public:
    int reverse(int x) {
        long n = 0;
        while(x!=0){
            n = x%10+10*n;
            x = x/10;
        }
        if (n>INT_MAX||n<INT_MIN){
            return 0;
        }
        return n;
    }
};

时间复杂度:O(logn)

反思:很简单的一道题目,但是一开始思考的时候就跑偏了,想用字符串来处理,造成了很多麻烦,但是也学习了很多东西。stringstream来处理string的强制转化;char array[]数组存储string数据;string的.length()和.c_str()方法;atoi(),atol()的字符串转数字的强制转换;如何设计自己函数。但是大方向的错误带来的是整体的复杂化,以后的头脑要清醒。

class Solution {
public:
    int reverse(int x) {
        
        int sign=1;
        int a=x,l=0;
        long result=0;
        stringstream ss;
        string str;
        if (x<0)
        {
            sign=-1;
            a=x*(-1);
        }
        ss<<a;
        ss>>str;
        l=str.length();
        char s[l];
        for (int i = 0; i < l; ++i)
        {
            s[i] = str[i];
        }
        rev(s,l);
        str=s;
        result=atol(str.c_str());
        result=result*sign;
        if (result>INT_MAX||result<INT_MIN){
            return 0;
        }
        return result;
    }

    void rev(char *s, int n){
        for (int i=0,j=n-1;i<j;i++,j--)
        {
            char c =s[i];
            s[i]=s[j];
            s[j]=c;
        }
    }
};





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值