LeetCode 7. Reverse Integer

7. Reverse Integer

一、问题描述

Reverse digits of an integer.

**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.

二、输入输出

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

三、解题思路

Integer To String

  • 首先单独处理0的情况,防止对正负判断造成影响。其实也没啥影响,不过还是喜欢单独处理特殊情况。
  • 然后记录下原输入是正数还是负数,并把x求绝对值。使用stringstream把abs(x)转换成string。
  • 要求把int反转,那么现在的最高位翻转后就是个位,反转前的个位就变成了最高位。依次遍历string 把每一位的值按照权重加起来求和。主要结果一定要使用long来保存,避免int越界的问题。
  • 最后还原原来的正负符号。并判断是否越界,包括超过最大值或者小于最小值。INT_MAX INT_MIN只能说不能更方便。
class Solution {
public:
    int reverse(int x) {
        if(x == 0)return 0;
        bool isPositive;
        if(x < 0)isPositive = false;
        else isPositive = true;
        stringstream ss;
        ss << abs(x);
        string str = ss.str();
        long ret = 0;
        for (int i = 0, n = str.size(); i < n; ++i) {
            ret += (str[i] - '0') * pow(10, i);
        }
        ret = isPositive ? ret : (-1)*ret;
        if(ret > INT_MAX || ret < INT_MIN){
            ret = 0;
        }
        return static_cast<int>(ret);
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值