leetcode第七题:Reverse Integer

题目:

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 store integers within the 32-bit signed integer range: [-2147483648,2147483647]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

解题思路:

该题目思路简单,要注意的是int类型的整数范围是[-2147483648,2147483647],因此当-2147483648和2147483647取反后将不再是int类型,因此解决该题目的思路是可以先将传进来的数值赋值给long long型变量,然后对long long型变量进行取反,如果取反后的数值大于INT_MAX,则应返回0。C++代码如下:

class Solution {
public:
    int reverse(int x) 
    {
        long long y = x;
        bool flag = true;
        if(y<0)
        {
            flag = false;
            y = -y;
        }
        long long res = 0;
        while(y>0)
        {
            res = res * 10+y % 10;
            y = y / 10;
        }
        if(res>INT_MAX)
        {
            return 0;
        }
        if(flag)
        {
            return res;
        }
        else
        {
            return -res;
        }
    }
};

运行结果:
leetcode第七题:Reverse Integer_第1张图片

你可能感兴趣的:(算法刷题,LeetCode,算法)