LeetCodeOJ_7_Reverse Integer

来源:互联网 发布:js新窗口打开url 编辑:程序博客网 时间:2024/06/06 04:03

答题链接

题目:

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?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Tags Math
Similar Problems (E) String to Integer (atoi)

分析:

(1)注意int的范围(32位)
min:-2147483648 max:2147483647

代码:

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

结果:

这里写图片描述

总结:

0 0
原创粉丝点击