C# Solution


  • 0
    J

    //C# Solution

    public int MyAtoi(string str)
    {
    int ans = 0, sign = 0;
    char[] chs;

            try
            {
                ans = Int32.Parse(str);
            }
            catch
            {
                chs = str.ToCharArray();
    
                
                foreach (char ch in chs)
                {
                    
                    if (!char.IsLetter(ch))
                    {
                        if(char.IsDigit(ch))
                        {
                            ans *= 10;
                            ans += (int)char.GetNumericValue(ch);
                        }
                        else if (ch == 45)
                        {
                            sign++;
                        }
    
                    }
                    else
                    {
                        break;
                    }
                }
            }
    
    
            if (sign % 2 == 1)
                ans *= -1;
    
            return ans;
        }

Log in to reply
 

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