您的位置:首页 > 其它

leetcode第二题-----Reverse Integer

2017-11-05 21:24 316 查看
Given a 32-bit signed integer, reverse digits of an integer.

Example 1:
Input: 123
Output:  321


Example 2:
Input: -123
Output: -321


Example 3:
Input: 120
Output: 21


Note:

Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

解法:声明一个int类型的数result,让它等于输入的数除以10的余数,此时result等于输入的数的最后一位,然后将输入的数不断整除10,通过求余求到最后一位,并将它添加到result的末尾。整个过程不断持续,直到输入的数最后一位添加到result中,这个判断条件为输入的数除以10为0。这个题目还要注意的是求出的相反数溢出的问题。这里有两种解法:一种是记录每次改变result之前的值,如果改变result之后的值除以10不等于改变result之前的值,那就说明溢出了。另外一种则是申明一个更大空间的数,然后最后判断它是否越过了int的范围即可。

下面的代码是第一种解法:

class Solution {

public:

    int reverse(int x) {

        if (x == -2147483648) 

                return 0;

        

        int sign = 0;

        

        if (x < 0) {

            sign = 1;

            x = -x;

        }

            int result = x%10;

            int check;

        

        while (x/10 > 0) {

            x = x/10;

            check =result;

            result = result*10+x%10;

            if (result/10 != check)

                return 0;

        }

        if (sign == 1)

            result = -result;

        return result;

    }

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: