zoukankan      html  css  js  c++  java
  • Reverse Integer

    Reverse Integer

    问题:

    Reverse digits of an integer.

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

    click to show spoilers.

    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.

    Update (2014-11-10):
    Test cases had been added to test the overflow behavior.

    思路:
      数字访问模板
    我的代码:
    public class Solution {
        public int reverse(int x) {
            int flag = x < 0 ? -1 : 1;
            long rst = 0;
            long num = x*flag;  
            while(num != 0)
            {
                rst = rst*10 + num%10;
                num /= 10;
            }
            if(rst * flag > Integer.MAX_VALUE || rst * flag < Integer.MIN_VALUE) return 0;
            return (int)rst * flag;
        }
    }
    View Code

    他人代码:

    public class Solution {
        public int reverse(int x) {
            long result =0;
            while(x != 0)
            {
                result = (result*10) + (x%10);
                if(result > Integer.MAX_VALUE) return 0;
                if(result < Integer.MIN_VALUE) return 0;
                x = x/10;
            }
            return (int)result;
        }
    }
    View Code

    学习之处:

    • 需要考虑到的Corner Case 太多了,主要有两点,对于Overflow的数据采用long代替int进行存储。
    • 没必要讨论是正数还是负数啊,负数也可以用进制访问的模板哒,这一点浪费了时间
    • 把超过进制判断语句放到循环里面,进一步节省时间,省的都Overflow了,还在继续进制访问。
  • 相关阅读:
    php根据时间显示刚刚,几分钟前,几小时前的实现代码
    PHP中获取当前页面的完整URL
    PhpExcel中文帮助手册|PhpExcel使用方法
    洛谷P1781 宇宙总统【排序+字符串】
    洛谷P1579 哥德巴赫猜想(升级版)【水题+素数】
    洛谷P1478 陶陶摘苹果(升级版)【水题】
    洛谷P1002 过河卒【dp】
    51Nod
    排序算法总结(C++)
    UVA1339
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4329370.html
Copyright © 2011-2022 走看看