ReverseInteger

Reverse digits of an integer.

成都创新互联坚持“要么做到,要么别承诺”的工作理念,服务领域包括:成都网站建设、做网站、企业官网、英文网站、手机端网站、网站推广等服务,满足客户于互联网时代的安仁网站设计、移动媒体设计的需求,帮助企业找到有效的互联网解决方案。努力成为您成熟可靠的网络建设合作伙伴!

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

click to show spoilers.

Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.


1.先记录符号
2.最后检查是否溢出int的范围


  1. class Solution {
  2.     public int reverse(int x) {
  3.         boolean flag=(x>=0)?true:false;
  4.         long data=1;
  5.         int[] arr=new int[10];
  6.         int index=0;
  7.         x=Math.abs(x);
  8.         while(x>0){
  9.             arr[index]=x % 10;
  10.             x=x/10;
  11.             index++;
  12.         }

  13.         long result=0L;
  14.         for(int i=index-1;i>=0;i--){
  15.             result=result+arr[i]*data;
  16.             data=data*10;
  17.         }
  18.         if(result>Integer.MAX_VALUE || result
  19.             return 0;
  20.         }
  21.         return flag==true?(int)result:-(int)result;
  22.     }
  23. }

网络答案

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


网页标题:ReverseInteger
当前网址:http://pwwzsj.com/article/jddcee.html