首页 > 其他 > 详细

leetcode笔记:Reverse Integer

时间:2016-01-01 19:01:26      阅读:172      评论:0      收藏:0      [点我收藏+]

一. 题目描述

Reverse digits of an integer.

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

二. 题目分析

反转一个整数,若为负数,则负号不变,然后反转负数。该题题设虽然简单,但隐藏一些陷阱,如反转后数字的溢出问题、低位为0时反转到高位时又怎么处理。这种题目目的不是为了考察某种算法,而是考察对各种边界条件是否考虑周全。这里的代码只是能Accept,不代表完美无缺。

三. 示例代码

class Solution
{
public:
    int reverse (int x)
    {
        long long result = 0;
        const int max = 0x7fffffff;  // int最大值  
        const int min = 0x80000000;  // int最小值

        for (; x != 0; x /= 10)
        {
            result = result * 10 + x % 10;
            if (result > max || result < min)
                result = 0; // 超出32位int的范围,置0 
        }

        return result;
    }
};

四. 小结

对于一些表面上看起来简单的题目,越是要重点考虑一些边界条件,而这些在笔试或面试时也能为你带来加分。

leetcode笔记:Reverse Integer

原文:http://blog.csdn.net/liyuefeilong/article/details/50444036

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!