新手区 7. Reverse Integer

沐芓李 · 2017年05月18日 · 最后由 沐芓李 回复于 2017年06月08日 · 1228 次阅读

题目描述

Reverse digits of an integer.

反转 int。
tips:
1.如果整数末尾包含 0,怎么输出,比如 10、100;
2.对于 int 反转后的整数,可能会越界。(如果整数越界则返回 0)

Example:

x = 123, return 321
x = -123, return -321

原文地址

思路方法

1.本题我是用 Python 做的,[ : : -1] 可以直接对字符串进行反转;
处理越界的问题,我使用 sys.maxsize,有问题。我也不知道为什么,最后就直接用的数字;

class Solution(object):
    def reverse(self, x):
        if x > 0:
            flag = 1
        else:
            flag = -1
        #把int整数转换为字符串
        strx = str(abs(x))
        #倒序字符串
        r = strx[::-1]
        res = flag * int(r)

        if res > 2147483647 or res < -2147483648:
            return 0
        else:
            return res

2.还有一种思路我并没有去实现,求各个权重的数值,然后重新分配权重。
伪代码如下:

#循序取各位数字
digit = x % 10
#不停的累乘,计算反转数字
ret = ret * 10 + digit
#去掉已经使用过的个位数
x = x / 10
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
共收到 4 条回复 时间 点赞
沐芓李 代码入门 中提及了此贴 05月18日 15:07
恒温 回复

恩呢,坚持~

ret 一直 *10,所以要预防 ret*10 后越界
java 代码如下:

public int reverse(int x) {
        int result = 0;
        while (x!=0){
            if(result>Integer.MAX_VALUE/10||result<Integer.MIN_VALUE/10)
                return  0;
            result = result*10 + x%10;
            x= x /10;
        }
        return  result;
    }
chenDoInG 回复

恩呢 我并没有实现这种方式
Python 也是有类似于Integer.MAX_VALUE表示最大值 但是我不知道为啥总是报错

需要 登录 后方可回复, 如果你还没有账号请点击这里 注册