[LeetCode] #7 Reverse Integer

#7 Reverse Integer

Question

Reverse digits of an integer.

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

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.

Note:

The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.

Thinking

此題比較麻煩的是要檢查Overflow,若偷懶一點可使用C#的關鍵字checked,在checked區塊內若數字發生Overflow會產生例外,這時候再用try catch去接就好了,寫法如下

public class Solution {
    public int Reverse(int x) {
        checked 
        {
            try
            {
                int result = 0;
                while (x != 0)
                {
                    var val = x % 10;
                    result = result * 10 + val;
                    x = x / 10;          
                }
                return result;       
            }
            catch(OverflowException)
            {
                return 0;
            }
        }
    }
}

那如果不想使用checked關鍵字,其實可以用點小技巧,即在運算完之後逆推回去,比較運算的前後值是否相等,若不相等則是發生Overflow,寫法如下

My C# Solution

public class Solution {
    public int Reverse(int x) {
        int result = 0;
        while (x != 0)
        {
            var val = x % 10;
            var temp = result * 10 + val;
            if ((temp-val) / 10 != result) return 0;
            result = temp;
            x = x / 10;       
        }
        return result;       
    }
}