zoukankan      html  css  js  c++  java
  • leetcode------Reverse Integer

    标题: Reverse Integer
    正确率: 34.8%
    难度 简单

    Reverse digits of an integer.

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

    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.

    这个题是我感觉我最能做出来的一道!但是我却用了很长时间。。主要卡在了越界问题上面,

    1、越界的主要问题是传进来的值一定不越界的,但是翻转过后的数值会出现越界的问题。

    2、int的界问题,由于我随便在网上查了下int的界被网上的错误答案所迷惑了。java int的范围应该是-2147483648   到2147483647  下界的绝对值是比上界的绝对值大的

    所以判断越界还是很重要的!!

    关键是怎么能快捷。

    特别是取余保存这个地方还有更更加简介的方式

    y=y*10+x%10;

    然后就是判断正负数了。

    这个题总体不难,不用讲太多的逻辑直接看代码就行:

     1 public class Solution {
     2     public int reverse(int x) {
     3         int negative=-1;
     4         boolean flag=false;
     5         if(x<10&&x>-10) return x;
     6         if(x==0) return 0;
     7         if(x<0){
     8             x*=-1;
     9             flag=true;
    10         } 
    11         long y = x%10;  
    12           if(y<0)return 0;
    13         while( x/10 != 0 ) {  
    14             x /= 10;  
    15             y *= 10;  
    16             y += x%10;  
    17         }
    18        if(y>(Integer.MAX_VALUE)) return 0;
    19         if(flag==true){
    20             return (int) (negative*y);
    21         }
    22         else
    23         return (int) y;
    24     
    25     }
    26 }
  • 相关阅读:
    C++调用web服务(java事例供参考)
    ASP.NET1.1与2.0如何引入MagicAjax (转载自http://hi.baidu.com/zzticzh)
    爱,在世界末日时
    Why Google Chrome is Multiprocess Architecture
    Chrome
    Code Reuse in Google Chrome
    Google V8 JavaScrit 研究(1)
    第一篇文章
    User Experience
    WPF
  • 原文地址:https://www.cnblogs.com/pkuYang/p/4160638.html
Copyright © 2011-2022 走看看