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 }
  • 相关阅读:
    EF写in
    1707. [Usaco2007 Nov]tanning分配防晒霜
    BZOJ 1706. [usaco2007 Nov]relays 奶牛接力跑
    1705. [Usaco2007 Nov]Telephone Wire 架设电话线
    BZOJ1704. [Usaco2007 Mar]Face The Right Way 自动转身机
    Codeforces Manthan, Codefest 19 (open for everyone, rated, Div. 1 + Div. 2)
    BZOJ1702. [Usaco2007 Mar]Gold Balanced Lineup 平衡的队列
    P2876 [USACO07JAN]解决问题Problem Solving
    BZOJ 1908. Pku2054 UVA1205 Color a Tree
    P4280 [AHOI2008]逆序对
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/3710643.html
Copyright © 2011-2022 走看看