【Leetcode】Reverse Integer

来源:互联网 发布:phpmyadmin软件 编辑:程序博客网 时间:2024/06/06 01:29

Reverse digits of an integer.

Example1: x = 123, return 321

Example2: x = -123, return -321


需要考虑的点是int类型的范围是-2147483648~2147483648.可能会出现溢出状况 ,这里使用longlong类型避免这种情况

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


0 0