zoukankan      html  css  js  c++  java
  • Leetcode: Reverse Integer

    Reverse digits of an integer.
    
    Example1: x = 123, return 321
    Example2: x = -123, return -321

    一次通过,它的spoiler里面的提示有两个:

    1. 末尾为0的情况,这个考虑到了

    2. 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?

    Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).

    最新的题目要求已经改成 assume that your function returns 0 when the reversed integer overflows. 简化了,

     1 public class Solution {
     2     public int reverse(int x) {
     3         boolean isNeg = false;
     4         if (x == 0) return x;
     5         if (x < 0) {
     6             isNeg = true;
     7             x = Math.abs(x);
     8         }
     9         int res = 0;
    10         while (x != 0) {
    11             int digit = x % 10;
    12             x = x / 10;
    13             if (res > (Integer.MAX_VALUE - digit) / 10) {
    14                 return 0;
    15             }
    16             res = res * 10 + digit;
    17         }
    18         return isNeg? -res : res;
    19     }
    20 }

    之前的题目没有设置overflow的test case,我们的处理是正数overflow就return Integer.MAX_VALUE,负数overflow就return Integer.MIN_VALUE. 参见下面Code Ganker的code。为了后面方便处理,先将数字转为正数。注意Integer.MIN_VALUE的绝对值是比Integer.MAX_VALUE大1的,所以经常要单独处理。如果不先转为正数也可以,只是在后面要对符号进行一下判断。这种题目考察的就是数字的基本处理,面试的时候尽量不能错,而且对于corner case要尽量进行考虑,一般来说都是面试的第一道门槛。

    Signed Long Integer有32位,其中最高位用来做符号位,剩下31位来做无符号的数值,表值范围是(0  -  2^30+2^29+2^28+...+2^1+2^0)即(0 - 2^31-1)即0 to 2147483647。 加上符号位,范围是–2147483648 to 2147483647

    推荐做法:


     
    1
    public int reverse(int x) { 2 if(x==Integer.MIN_VALUE) 3 return Integer.MIN_VALUE; 4 int num = Math.abs(x); 5 int res = 0; 6 while(num!=0) 7 { 8 if(res>(Integer.MAX_VALUE-num%10)/10) 9 return x>0?Integer.MAX_VALUE:Integer.MIN_VALUE; 10 res = res*10+num%10; 11 num /= 10; 12 } 13 return x>0?res:-res; 14 }
  • 相关阅读:
    近来有客户要求用table显示一大串数据,由于滚动后就看不到表头,很不方便,所以想到这个效果。
    js如何取当前日期时间/格式为:yyyymmdd hh:mm:ss
    jdk源码分析 – Thread线程类源码分析
    Swing中的MVC
    编程生涯的一次思想总结
    怎样成为高手
    浅谈测试驱动开发(TDD)
    Java RMI之HelloWorld篇(EJB都是建立在rmi基础之上的)
    Swing框架之Model
    EJB 工作原理
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/3710643.html
Copyright © 2011-2022 走看看