c# version


  • 0
    R
    int atoi(string str)
    {
    	if(string.IsNullOrEmpty(str)) return 0;
    	int num = 0, index = 0;
    	while (index < str.Length && str[index] == ' ')
    	{
    		index++;
    	}
    	bool isNeg = false;
    	bool containsSpecial = false;
    	if (str[index] == '-') { isNeg = true; containsSpecial = true; }
    	if (str[index] == '+') { isNeg = false; containsSpecial = true; }
    	if(containsSpecial) index++;
    	while (index < str.Length)
    	{
    		if ((int)str[index] >= (int)'0' && (int)str[index] <= (int)'9')
    		{
    			try { num = checked(num * 10 + (str[index] - (int)'0')); index++; }
    			catch (OverflowException)
    			{
    				return isNeg ? Int32.MinValue : Int32.MaxValue;
    			}			
    		}		
    		else break;
    	}
    	return isNeg ? -1 * num : num;
    }
    

Log in to reply
 

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