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 }
  • 相关阅读:
    poj 2187 Beauty Contest(旋转卡壳)
    poj 2540 Hotter Colder(极角计算半平面交)
    poj 1279 Art Gallery(利用极角计算半平面交)
    poj 3384 Feng Shui(半平面交的联机算法)
    poj 1151 Atlantis(矩形面积并)
    zoj 1659 Mobile Phone Coverage(矩形面积并)
    uva 10213 How Many Pieces of Land (欧拉公式计算多面体)
    uva 190 Circle Through Three Points(三点求外心)
    zoj 1280 Intersecting Lines(两直线交点)
    poj 1041 John's trip(欧拉回路)
  • 原文地址:https://www.cnblogs.com/pkuYang/p/4160638.html
Copyright © 2011-2022 走看看