LeetCode 7 反转数字

来源:互联网 发布:js undefined判断 编辑:程序博客网 时间:2024/06/05 20:04

这道题很简单但是比较烦人 关键在于对反转后的数字溢出问题处理 我用了int64来存储结果,然后判断


c# code

public class Solution
{
    public int Reverse(int x)
    {
        string str = x.ToString();
        string s="";
        int i;
        if(str[0]=='-')
        {
            i=1;
            s+=str[0];
        }
        else
        {
            i=0;
        }
        int pos=str.Length-1;
        while(pos>=i)
        {
            s+=str[pos];
            pos--;
        }
        if (Convert.ToInt64(s) > int.MaxValue || Convert.ToInt64(s)<int.MinValue)
        {
            return 0;
        }
        else
        {
            return Convert.ToInt32(s);
        }
    }
}


0 0