代码改变世界

LeetCode-7-反转整数-c# 版本

2018-08-27 03:45  撞破南墙  阅读(875)  评论(0编辑  收藏  举报

c# 版本

// 给定一个 32 位有符号整数,将整数中的数字进行反转。
public class Solution
{
public int Reverse(int x)
{
/*
// 边界判断
// x变成字符串,然后拼接字符串。
如果第一位是-,则将其放到第一位。
从后往前遍历
如果遇到0则无视
*/
if (x >= Int32.MaxValue || x < Int32.MinValue)
{
return 0;
}

        StringBuilder sb1 = new StringBuilder();
        string x_str = x.ToString();
        if (x_str[0] == '-')
        {
            sb1.Append("-");
        }
        bool start_not_zero = false;
        for (int i = x_str.Length - 1; i >= 0; i--)
        {
            if (i == 0 && x_str[i] == '-')// 第一位
            {
                continue;
            }
            if (x_str[i] == 0 && start_not_zero == false)// 最后一位是0
            {
                start_not_zero = false;
                continue;
            }
            else
            {
                start_not_zero = true;
            }

            sb1.Append(x_str[i]);

        }

        long x1 = Int64.Parse(sb1.ToString());
        if (x1 >= Int32.MaxValue || x1 < Int32.MinValue)
        {
            return 0;
        }
        return (int)x1;


    }
}