Sharing my C# solution (94th percentile) for atoi


  • 0
    B

    This one took me forever to handle all of the cases. Probably would have missed some/many of them in a real interview, but anyway, I ended up with this solution which is apparently faster than 94% of all submitted solutions, so I feel OK about myself. Regardless, I think my solution is pretty hard to read and maybe a little convoluted, maybe someone else has a cleaner way of doing this?

    public int MyAtoi(string str) {
            if (str == null) {
               return 0;
            }
    
            char[] chars = str.ToCharArray();
            double result = 0;
            int firstIndex = 0;
            int lastIndex = chars.Length - 1;
            bool isNegative = false;
            bool foundSign = false;
            bool foundDigits = false;
            for (int i = 0; i < chars.Length; i++) {
               if (!foundSign && (chars[i] == '-' || chars[i] == '+')) {
                  foundSign = true;
                  isNegative = chars[i] == '-';
               } else if (chars[i] >= '0' && chars[i] <= '9') {
                  if (!foundDigits) {
                     foundDigits = true;
                     firstIndex = i;
                  }
                  lastIndex = i;
               } else if (foundDigits && (chars[i] < '0' || chars[i] > '9')) {
                  break;
               } else if (!foundSign && !foundDigits && chars[i] == ' ') {
                  continue;
               } else {
                  return 0;
               }
            }
            
            if (!foundDigits) {
               return 0;
            }
    
            for (int i = lastIndex, pow = 0; i >= firstIndex; i--, pow++) {
               int convertedDigit = (int)chars[i] - (int)'0';
               result += Math.Pow(10, pow) * convertedDigit;
            }
    
            if (isNegative) {
               result *= -1;
            }
    
            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.