LeetCode 8 字符串转数字

很简单的一道题 就是对非法输入和溢出问题的处理比较麻烦 所以造成了该题的AC很低...


c# code


public class Solution
{
    public int MyAtoi(string str)
    {
        double ret;
        str = str.Trim();
        try
        {
            string s = "";
            int a = 0;
            int i = str[0] == '-' || str[0] == '+' ? 1 : 0;
            s += str[0] == '-' ? "-" : "";
            while (i < str.Length && int.TryParse(str[i].ToString(), out a))
            {
                s += str[i];
                i++;
            }
            ret = Convert.ToDouble(s);
        }
        catch
        {
            ret = 0;
        }
        if (ret > int.MaxValue)
        {
            return int.MaxValue;
        }
        else if (ret < int.MinValue)
        {
            return int.MinValue;
        }
        else if (ret > ulong.MaxValue)// || ret < Convert.ToInt64(9223372036854775809))
        {
            return 0;
        }
        else
        {
            return Convert.ToInt32(ret);
        }
    }
}



你可能感兴趣的:(C#,c#,字符串转数字)