zoukankan      html  css  js  c++  java
  • My first_leetcode_Rever Ingeter 数字翻转java实现(办法集合)

    7. Reverse Integer

    Reverse digits of an integer. 

    Example1: x = 123, return 321 
    Example2: x = -123, return -321 
    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. 
    Note: 
    The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
    一个整数的各个位数翻转. 
     
    例1: x = 123, return 321 
    例2: x = -123, return -321 
    如果整数的最后一位是0,输出应该是什么?比如10,100. 
    你注意到翻转的整数可能溢出吗?假设输入是32位整数,那么10000000003的翻转会溢出.该如何处理这个? 
    因为这个问题,当翻转之后溢出时,方程应该返回0. 
     
    思路:
    1.土办法,判断字符输入是否合法,有无+ - 号和多余字符,是否在int 的int_MAX和int_MIN区间范围内,只有在范围内的数字才可以被翻转
    2.int型的范围是-2147483648~2147483647,如果你的数字绝对值翻转前不越界,翻转后也有可能越界了,负数的情况也是如此, 比如1000 000 009
    3.翻转的时候只需要考虑绝对值翻转后加上符号即可
    class Solution {
    public int reverse(int x) {
            int res = 0;
            while (x != 0) {
                if (Math.abs(res) > Integer.MAX_VALUE / 10) return 0;
                res = res * 10 + x % 10;
                x /= 10;
            }
            return res;
        }
    };

    这个办法可以解决一般的情况,但是当数字足够大到达边界值周围的时候需要会报错

    我们在这里要做一个改造,增加判断临界值时 的情况

    参考地址:http://www.jiuzhang.com/solution/reverse-integer/

    参考地址:http://www.cnblogs.com/grandyang/p/4125588.html

    刚开始搞,很多东西玩的不是很透彻,欢迎大家相互讨论哈

     
    不积跬步无以至千里,千里之堤毁于蚁穴。 你是点滴积累成就你,你的丝丝懒惰毁掉你。 与诸君共勉
  • 相关阅读:
    C#代码也VB
    Flash/Flex学习笔记(9):ActionScript3.0与Javascript的相互调用
    原来Silverlight 4中是可以玩UDP的!
    Flash/Flex学习笔记(20):贝塞尔曲线
    Flash/Flex学习笔记(16):如何做自定义Loading加载其它swf
    AS3:让人叹为观止的Flash作品
    Flash/Flex学习笔记(10):FMS 3.5之Hello World!
    Flash/Flex学习笔记(12):FMS 3.5之如何做视频实时直播
    Flash/Flex学习笔记(28):动态文本的滚动控制
    Flash/Flex学习笔记(18):画线及三角函数的基本使用
  • 原文地址:https://www.cnblogs.com/haoHaoStudyShare/p/7301875.html
Copyright © 2011-2022 走看看