Remember to check overflows.

 1 class Solution {
 2 public:
 3     int reverse(int x) {
 4         int sign = x < 0 ? -1 : 1, result = 0;
 5         x = fabs(x);
 6         while (x > 0) {
 7             if (result > (INT_MAX - x%10)/10) {
 8                 return 0;
 9             }
10             result = result*10 + x%10;
11             x /= 10;
12         }
13         return sign * result;
14     }
15 };

 

posted on 2015-03-23 05:55  keepshuatishuati  阅读(92)  评论(0编辑  收藏  举报