Leetcode 7 Reverse Integer

时间:2015-02-15 12:01:46   收藏:0   阅读:104

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 }

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!