C# solution: check all corner cases


  • 0
    B
    public class Solution 
    {
        public enum Sign { Positive, Negative }
        public int MyAtoi(string str) 
        {
            var nonBlankStartIndex = 0;
    
            for (int i = 0; i < str.Length; i++)
            {
                if (str[i] == ' ')
                {
                    nonBlankStartIndex++;
                }
                else
                {
                    break;
                }
            }
    
            if (nonBlankStartIndex == str.Length) return 0;
    
            var firstChar = str[nonBlankStartIndex];
    
            if (firstChar != '+' && firstChar != '-' && !Char.IsNumber(firstChar))  return 0;
    
            var sign = Sign.Positive;
    
            long result = 0;
    
            for(int i = nonBlankStartIndex; i < str.Length; i++)
            {
                var curChar = str[i];
                
                if (i == nonBlankStartIndex)
                {
                    if (curChar == '+')
                    {
                        sign = Sign.Positive;
                    }
                    else if (curChar == '-')
                    {
                        sign = Sign.Negative;
                    }
                    else
                    {
                        result = GetResult(result, sign, curChar);
                    }
                }
                else
                {
                    if (!Char.IsNumber(curChar)) break;
    
                    result = GetResult(result, sign, curChar);
    
                    if (result > int.MaxValue) return int.MaxValue;
                    if (result < int.MinValue) return int.MinValue;
                }
            }
    
            return (int)result;
        }
        
        private long GetResult(long curResult, Sign sign, char numberChar)
        {
            int curNumber = sign == Sign.Positive ? numberChar - '0' : -(numberChar - '0');
    
            return curResult * 10 + curNumber;
        }
    }
    

Log in to reply
 

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