C# assume this one is hard


  • 0
    Y

    public class Solution {
    public int MyAtoi(string str) {

        //check null
        if(string.IsNullOrEmpty(str))
            return 0;
        
        //trim
        str=str.Trim();
        
        //consider all the senarioes
        var dictionary=new Dictionary<char,int>();
        
        dictionary.Add('1', 1);
        dictionary.Add('2', 2);
        dictionary.Add('3', 3);
        dictionary.Add('4', 4);
        dictionary.Add('5', 5);
        dictionary.Add('6', 6);
        dictionary.Add('7', 7);
        dictionary.Add('8', 8);
        dictionary.Add('9', 9);
        dictionary.Add('0', 0);
        
        //check minus and 
        int i = str.StartsWith("-") || str.StartsWith("+") ? 1 : 0;
        
        long result=0;
        
        for(; i<str.Length; i++)
        {
            if(!dictionary.ContainsKey(str[i]))
                break;
            
            if(result > int.MaxValue/10)
            {
                if(str.StartsWith("-"))
                {return int.MinValue;}
                else
                {
                    return int.MaxValue;
                }
                
            }
            
            result = result*10 + dictionary[str[i]];
        }
        
        
        if(str.StartsWith("-"))
            result=0-result;
        
        if(result>int.MaxValue)
            return int.MaxValue;
        
        if(result<int.MinValue)
            return int.MinValue;
        
        return (int)result;
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
    }
    

    }


Log in to reply
 

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