zoukankan      html  css  js  c++  java
  • LeetCode 7. Reverse Integer (倒转数字)

    Given a 32-bit signed integer, reverse digits of an integer.

    Example 1:

    Input: 123
    Output:  321
    

    Example 2:

    Input: -123
    Output: -321
    

    Example 3:

    Input: 120
    Output: 21
    

    Note:
    Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.


    题目标签:Math
      题目给了我们一个int 数字,让我们倒转它。
      利用 % 10 来拿到最右边数字,然后每次把res * 10 加上新拿到的数字,利用 x / 10 来遍历剩下的数字。
      这一题关键在于,如何检查 overflow,可以利用long,但是如果题目给你的是long,那你如何检查long 是否overflow呢。所以要在不使用更大的type的情况下来检查。
     
      新的res 是如何产生的:
        newRes = res * 10 + x % 10;
      那么如果新的res 没有overflow 的话,把newRes 倒推回去应该是和旧的 res 相等的:
        (newRes - x % 10) / 10 == res
      利用这一点,如果overflow的话,那么倒退回去肯定是 不相等的。
     
     
     
     

    Java Solution:

    Runtime beats 80.84% 

    完成日期:06/12/2017

    关键词:reverse int

    关键点:% 10; / 10

     1 class Solution 
     2 {
     3     public int reverse(int x) 
     4     {
     5         int res = 0;
     6            
     7         while(x != 0)
     8         {
     9             int tail = x % 10;
    10             int newRes = res * 10 + tail;
    11             
    12             if((newRes - tail) / 10 != res) // check overflow
    13                 return 0;
    14             
    15             res = newRes;
    16             x = x / 10;
    17         }
    18         
    19     
    20         return res;
    21     }
    22 }

    参考资料:https://discuss.leetcode.com/topic/6104/my-accepted-15-lines-of-code-for-java

    LeetCode 题目列表 - LeetCode Questions List

    题目来源:https://leetcode.com/

  • 相关阅读:
    Reusable action with query database
    Oracle实现分组统计记录
    Oracle行列转换的几种实现方法
    junit私有方法测试
    Junit实现抽象类测试(二)
    C++的性能C#的产能?! .Net Native 系列《二》:.NET Native开发流程详解
    C++的性能C#的产能?! .Net Native 系列向导
    c++的性能, c#的产能?!鱼和熊掌可以兼得,.NET NATIVE初窥
    辞职敬礼
    WPF 心路历程
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/8016130.html
Copyright © 2011-2022 走看看