Reverse Integer

来源:互联网 发布:手机卡盟源码 编辑:程序博客网 时间:2024/05/22 07:40
题目:

Reverse digits of an integer.

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

一般来说整数的处理问题要注意的有两点,一点是符号,另一点是整数越界问题。

对于32位整数,1000000003 的翻转就是越界的。

public static int reverse(int x) {if(x==Integer.MIN_VALUE)          return 0;      int num = Math.abs(x);      int res = 0;      while(num!=0)      {          if(res>(Integer.MAX_VALUE-num%10)/10)              return 0;          res = res*10+num%10;          num /= 10;      }      return x>0?res:-res; }


0 0
原创粉丝点击