[leetcode] Reverse Integer

来源:互联网 发布:录制视频软件加快 编辑:程序博客网 时间:2024/04/28 12:58

Reverse digits of an integer.

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

Have you thought about this?

Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).

class Solution {public:    int reverse(int x) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        int flag=1;        if(x<0){            flag=-1;            x=x*flag;        }        int temp=0;        for( ; x/10!=0 ; x=x/10){            temp=temp*10+x%10;//考虑溢出的问题        }        if(temp*10/10!=temp)            return 0;        temp=temp*10;        if((temp+x%10-x%10)!=temp)            return 0;        temp=temp+x%10;        return flag*temp;    }};


原创粉丝点击