zoukankan      html  css  js  c++  java
  • Reverse Integer

    1. Question

    反转一个整数的数位(注意溢出情况)

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

    2. Solution

    2.1 整除取余法

     1 public class Solution {
     2     public int reverse( int x ){
     3         int m = x;
     4         long res = 0;
     5         while( m!=0 ){
     6             res = res * 10 + m % 10;
     7             m /= 10;
     8         }
     9         if( res > Integer.MAX_VALUE || res < Integer.MIN_VALUE )
    10             return 0;
    11         return (int)res;
    12     }
    13 }
    View Code

    2.2 字符串方法

     1 //可以直接用String的reverse方法,但是效率低
     2 public class Solution {
     3     public int reverse( int x ){
     4         String orig = String.valueOf(Math.abs(x));
     5         StringBuilder res = new StringBuilder();
     6         if( x<0 )
     7             res.append('-');
     8         for( int i=orig.length()-1; i>=0 ; i-- )
     9             res.append( orig.charAt(i) );
    10         try{
    11             x = Integer.parseInt(res.toString());
    12         }catch( NumberFormatException e ){
    13             x = 0;
    14         }
    15         return x;
    16     }
    17 }
    View Code

    3. 复杂度分析

    O(n)

  • 相关阅读:
    hdu5412CRB and Queries
    LCA rmq st model
    HDU 5348 MZL's endless loop
    2015多校联合训练赛 Training Contest 4 1008
    Bestcoder Tom and matrix
    TOJ 4105
    Codeforces D. Iahub and Xors
    Set 技巧之一
    1036: [ZJOI2008]树的统计Count
    一点点VIM
  • 原文地址:https://www.cnblogs.com/hf-cherish/p/4572773.html
Copyright © 2011-2022 走看看