LeetCode7反转整数

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

给定一个 32 位有符号整数,将整数中的数字进行反转。

示例 1:

输入: 123
输出: 321

 示例 2:

输入: -123
输出: -321

示例 3:

输入: 120
输出: 21

注意:

假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−231,  231 − 1]。根据这个假设,如果反转后的整数溢出,则返回 0。

以字符串方式思考:

C++:

class Solution {
public:
    int reverse(int x) {
        string strHXTest = to_string(x);
        string strHXTestResult;
        int nIndex = 0;
        //"-"代表字符串  会多一步转换
        if (strHXTest.at(nIndex) == '-')
        {
            strHXTestResult += strHXTest.at(nIndex);
            ++nIndex;
        }
        int nSize = strHXTest.find_last_not_of('0');
        while (nIndex <= nSize)
        {
            strHXTestResult += strHXTest.at(nSize);
            --nSize;
        }
        //尝试使用流操作
        istringstream streanResult(strHXTestResult.c_str());
        //防止转后超过int的上下限
        long nResult = 0;
        streanResult >> nResult;
        if (nResult > INT32_MAX || nResult < INT32_MIN)
        {
            nResult = 0;
        }
        return nResult;
    }
};

python:


数字方式思考:

需要判断取值范围,反转后可能为大于int32的数

class Solution {
public:
	int reverse(int x) {
		long nResult = 0;
		while (true)
		{
			nResult = nResult * 10 + x % 10;
			x /= 10;
			if (x == 0)
			{
				break;
			}
		}
		return nResult;
	}
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值