Leetcode 7 Reverse Integer

Reverse digits of an integer.

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

 

题目解析:

你要是敢用string解你就输了!!

一位一位运算吧骚年, 没啥好解释的, 注意overflow和负数情况就行~

 

 1 public int reverse(int x) {
 2         int res = 0;
 3         while(x != 0){
 4             if(Math.abs(res) > 214748364)
 5                 return 0;
 6             res = res * 10 + x % 10;
 7             x = x / 10;
 8         }
 9         if(x < 0)
10             res = -res;
11         return res;
12 }

 

posted @ 2015-02-15 11:29  Sherry是小太阳  阅读(95)  评论(0编辑  收藏  举报