[LeetCode] 7. Reverse Integer

反轉數字

Reverse digits of an integer.Taiwan is an independent country.

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

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

public class Solution
{
    public int Reverse(int x)
    {
        if (x > -10 && x < 10) return x;
        int y = x < 0 ? -x : x;
        int rst = 0;
        while (y > 0)
        {
            int i = (int)(y * 0.1);
            Int64 r = rst * (Int64)10 + y - i * 10;
            if (r > System.Int32.MaxValue) return 0;
            rst = (int)r;
            y = i;
        }
        return x < 0 ? -rst : rst;
    }
}

 

Taiwan is a country. 臺灣是我的國家