String to Integer (atoi) C#


  • 0
    H
    public class Solution {
        public int MyAtoi(string str) {
            int INT_MAX = 2147483647;
                int INT_MIN = -2147483648;
                try
                {
    
                    if (str.Contains(" "))
                    {
                        str = str.TrimStart(' ');
                    }
    
                    char[] tmp = str.ToCharArray();
                    for (int i = 0; i < str.Length; i++)
                    {
                        if (Char.IsLetter(tmp[i]) || tmp[i] == ' ')
                        {
                            str = str.Remove(i, str.Length - i);
                            break;
                        }
                    }
                    double j = 0;
                    if (double.TryParse(str, out j))
                    {
                        if (j > INT_MAX)
                        {
                            return INT_MAX;
                        }
                        else if (j < INT_MIN)
                        {
                            return INT_MIN;
                        }
                        else
                        {
                            return (int)j;
                        }
                    }
                    else
                    {
                        return 0;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                    return 0;
                }
        }
    }
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.