leetcode_7. Reverse Integer

来源:互联网 发布:itudou是什么软件 编辑:程序博客网 时间:2024/06/05 11:22

题目:

Reverse digits of an integer.

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

click to show spoilers.

Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.

Subscribe to see which companies asked this question.

简单题:就是输入一个数,反转它的数值。如果超过了int32,就return 0


class Solution {
public:
    int reverse(int x) {
        long long ans=0;
        if(x==0){
            return 0;
        } else if(x<0){
           // ans=ans*(-1);
            int y=-x;
            while(y){
                int k=y%10;
                y=y/10;
                ans=ans*10+k;
            }
            if (ans > INT_MAX || ans < INT_MIN){
                return 0;
            }
            return -ans;
        } else {
            int y=x;
            while(y){
                int k=y%10;
                y=y/10;
                ans=ans*10+k;
            }
            if (ans > INT_MAX || ans < INT_MIN){
                return 0;
            }
            return ans;
        }
    }
};

0 0