ReverseInteger-创新互联

Reverse digits of an integer.

创新互联建站主营龙潭网站建设的网络公司,主营网站建设方案,重庆APP开发公司,龙潭h5小程序开发搭建,龙潭网站营销推广欢迎龙潭等地区企业咨询

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. }

文章名称:ReverseInteger-创新互联
文章链接:http://pwwzsj.com/article/hojsg.html