LeetCode 7. Reverse Integer

本文介绍了一个简单的整数反转算法,并提供了C++实现代码。该算法能够处理正数、负数及溢出情况,通过判断反转后的最后一位数字是否发生变化来检测溢出。文章通过实例演示了如何使用该算法。

Reverse digits of an integer.

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

Need to pay attention to negative numbers.... and overflow case.

Here, the overflow case is handled neatly!  If it is overflowed, the last digit wont be the same as before......

#include <iostream>
#include <algorithm>
using namespace std;

int reverse(int x) {
    int i = 0;
    bool negative = false;
    if(x < 0)  negative = true;
    x = abs(x);
    int res = 0;
    while(x) {
        int tmp = x % 10;
        res = res * 10 + tmp;
        if(res % 10 != tmp) return 0;   // if overflowed, the last digit will sure be changed.
        x = x / 10;
    }
    return negative ? -res : res;
}

int main(void) {
    int num  = -123;
    cout << reverse(num) << endl;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值