LeetCode Reverse Integer

class Solution {
public:
    int reverse(int x) {
        bool neg = x < 0;
        long long num = x;
        if (neg) num = -num;
        long long out = 0;
        while (num) {
            out = out * 10 + num % 10;
            num /= 10;
        }
        if (neg) return -out;
        return out;
    }
};

再水

第二轮:

Reverse digits of an integer.

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

click to show spoilers.

Have you thought about this?

Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Update (2014-11-10):
Test cases had been added to test the overflow behavior.

用int来做:

 1 class Solution {
 2 public:
 3     int reverse(int x) {
 4         int val = 0;
 5         int pos_threshold = INT_MAX/10;
 6         int neg_threshold = INT_MIN/10;
 7         bool positive = x >= 0;
 8         while (x) {
 9             int d = x % 10;
10             if (positive) {
11                 if (val > pos_threshold) {
12                     val = 0;
13                     break;
14                 }
15             } else {
16                 if (val < neg_threshold) {
17                     val = 0;
18                     break;
19                 }
20             }
21             val = val * 10 + d;
22             
23             x = x / 10;
24         }
25         return val;
26     }
27 };

因为是数字逆转,原来的输入数据也是在int范围内,所以如果数字长度是10位则第一位也只能是1或者2,所以只需判断前一次的结果值是否比threshold大/小就行

 

posted @ 2014-06-24 14:34  卖程序的小歪  阅读(150)  评论(0编辑  收藏  举报