[leetcode]Reverse Integer C语言

本文介绍了一种整数反转的方法,并详细讨论了如何处理反转过程中可能出现的溢出问题。通过使用long long类型的变量来存放转换后的值,确保了在32位整数范围内反转操作的正确性。

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

【题】
Reverse digits of an integer.

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

click to show spoilers.
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.
【题目分析】
这道题主要是对于溢出情况的处理。用long long类型的变量存放转换后的值。
【具体代码如下】

int reverse(int x) {
    if(x==0)return 0;
    int sign=1;
    int pox_x;
    if(x>0)pox_x=x;
    else 
    {   
        sign=-1;
        pox_x=-x;
    }
    int rev_x;
    if(x%10==0)return reverse(x/10);
    int number[10];
    int i=0;
    int digits=0;
    while(pox_x>0)
    {
        number[i]=pox_x%10;
        pox_x=pox_x/10;
        i++;
    }
    int j=0;
    long long count=0;
    while(j<i)
        {
            count=count*10+number[j];
            j++;
        }
        if(count>2147483647)return 0;
        else rev_x=count;
        return rev_x*sign;

}

【个人总结】
其实这道题我的解法是过于麻烦了。首先,对于x=1000这类情况,可以不用另外分情况讨论,递归的求解导致时间花费多。其次,当确定用 long long 类型后,不用新建一个number[10]数组,因为int型最大就是10位数,而long long 范围是 -9223372036854775808 ~ +9223372036854775807 ,它占用8个字节。所以这点上处理不恰当,啰嗦冗余。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值