关闭

LeetCodeOJ_7_Reverse Integer

标签: OJ算法c++
144人阅读 评论(0) 收藏 举报
分类:

答题链接

题目:

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

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:7104次
    • 积分:362
    • 等级:
    • 排名:千里之外
    • 原创:32篇
    • 转载:3篇
    • 译文:0篇
    • 评论:0条