7. Reverse Integer

来源:互联网 发布:蒙古入侵日本知乎 编辑:程序博客网 时间:2024/05/17 01:06

Reverse digits of an integer.

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

class Solution {public:    int reverse(int x) {        int flag = 1;        int newx = 0;        //if(x<0) {flag = -1; x = -x;}        while(x/10){            newx = newx*10+x%10;            if(abs(newx)>INT_MAX/10) return 0;            else if(abs(newx)==INT_MAX/10&&(x/10>7||x/10<-8)) return 0;            else x /= 10;                    }        return newx = newx*10+x%10;    } };
心得:题目的难点在于要考虑 溢出情况,上界2147483647下界-2147483648

运行速度:快;

0 0
原创粉丝点击