[LeetCode] #7 Reverse Integer

Reverse digits of an integer.

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

题目很简单,先判断数字的正负,再按位倒置数字就可以了。不过要考虑int的上限。时间:16ms

代码如下:

class Solution {
public:
    int reverse(int x) {
        bool sign = x > 0 ? false : true;
        int temp = x > 0 ? x : 0-x;
        long long y = 0;
        
        while (temp){
            y = y * 10 + temp % 10;
            temp = temp / 10;
        }
        if (y > 2147483647 || (0- y > 2147483648))
            return 0;
        if (sign == true)
            y = 0 - y;
        return y;
    }
};
“If you give someone a program, you will frustrate them for a day; if you teach them how to program, you will frustrate them for a lifetime.”
原文地址:https://www.cnblogs.com/Scorpio989/p/4412305.html