My solution in C#


  • 0
    A
    public class Solution {
    public int MyAtoi(string str) {
        if(string.IsNullOrEmpty(str)) return 0;
        str=str.Trim();
        long returnval=0;
        int Sign=1;
        char[] chars=str.ToCharArray();
    
        
        if(chars[0]=='-') Sign=-1;
        else if(chars[0]!='+') 
        {
            if(char.GetNumericValue(chars[0])==-1) return 0;
            
            returnval = returnval * 10 +(int)Char.GetNumericValue(chars[0]);
        }
        
        if (chars.Length==1 || char.GetNumericValue(chars[1])==-1) return (int)returnval;
        returnval = (returnval * 10 +(int)Char.GetNumericValue(chars[1]))*Sign;
    
        for(int i=2;i<chars.Length;i++)
        {
            if(char.GetNumericValue(chars[i])==-1) break;
    
            if(Sign==1)
            {
                returnval = returnval * 10 +(int)Char.GetNumericValue(chars[i]);
                if (returnval>Int32.MaxValue) return Int32.MaxValue;
                
            }
            else
            {
                returnval = returnval * 10 -(int)Char.GetNumericValue(chars[i]);
                if(returnval<Int32.MinValue) return Int32.MinValue;
            }
    
        }
       
        return (int)returnval;
        
    }
    

    }


Log in to reply
 

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