代码改变世界

[LeetCode #7] Reverse integer

2016-10-01 11:40  amadis  阅读(131)  评论(0编辑  收藏  举报

Reverse digits of an integer.

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

 1 // refer to http://bangbingsyb.blogspot.com/search?q=Reverse+Integer
 2 class Solution {
 3 public:
 4     int reverse(int x) {
 5         int ret = 0;
 6         while (x != 0) {
 7         // handle overflow/underflow
 8             if (abs(ret) > 214748364) return 0;
 9             ret = ret * 10 + x % 10;
10             x /= 10;
11         }
12         return ret;
13     }
14 };