C# try/catch solution


  • 0
    B

    Probably not the most innovative, but it works

    public class Solution {
        public int MyAtoi(string str) {
            // Return 0 if no input
            if (str.Length == 0) return 0;
        
            // Triming whitespace at the head of the string    
            int k = 0;
            while (str[k] == 32) k++;
            string trimStr = str.Substring(k, str.Length-k);
    
            // Break the integer parse off where the first space or character value is observed        
            int breakOff = trimStr.Length;
            for (int i = 0; i < trimStr.Length; i++)
            {
                if ((int)trimStr[i] > 57 || (int)trimStr[i] == 32) 
                {
                    breakOff = i;
                    break;
                }
            }
            string subStr = trimStr.Substring(0, breakOff);
            
            // Parse the value
            try
            {
                Int32.Parse(subStr);
            }
            // Catch format exceptions ("+", "((@#%)", etc.)
            catch (FormatException)
            {
                return 0;
            }
            // Catching overflow errors and return min/max value according to sign
            catch (OverflowException)
            {
                if (subStr[0] == 45)
                {
                    return Int32.MinValue;
                }
                else
                {
                    return Int32.MaxValue;
                }
            }
            
            return Int32.Parse(subStr);
        }
    }
    

Log in to reply
 

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