[LeetCode]7. Reverse Integer

本文介绍了解决LeetCode上第7题“整数反转”的两种方法:一种是将整数转换为字符串后进行反转;另一种是通过循环操作直接对整数进行反转。并提供了完整的C++代码实现。

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

[LeetCode]7. Reverse Integer

题目描述

这里写图片描述

思路

转字符串,逆转
直接对整数循环逆转

代码

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

class Solution {
public:
    int reverse(int x) {
        /*
        if (x == INT_MIN)
            return 0;
        string res = "";
        if (x < 0){
            res += "-";
            x = abs(x);
        }
        string s = to_string(x);
        for (int i = 0; i < s.size() / 2; ++i)
            swap(s[i], s[s.size() - i - 1]);
        string s_max = to_string(INT_MAX);
        res = res + s;
        if (s.size() >= s_max.size() && s > s_max)
            return 0;
        return stoi(res);
        */
        int res = 0;
        while (x) {
            int temp = res * 10 + x % 10;
            if (temp / 10 != res)
                return 0;
            res = temp;
            x /= 10;
        }
        return res;
    }
};

int main() {
    Solution s;
    cout << s.reverse(123) << endl;
    system("pause");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值