Problem of the Day
A new programming or logic puzzle every Mon-Fri

parseInt

Continuing on with the theme of numbers, can you reimplement a basic implementation of parseInt? Our function will take in a string and return an integer representation of that string if one exists. Otherwise you can throw an error or return not a number. It's safe to assume that the input will be of base 10 but for bonus points I encourage you to support multiple bases as does the real parseInt.

parseInt('444') -> 444
parseInt('J3110') -> throw error or return NaN

Permalink: http://problemotd.com/problem/parseint/

Comments:

  • Anonymous - 10 years, 1 month ago

    def parseInt(st):
        res = 0
        for ch in st:
            if not '0' <= ch <= '9':
                raise ValueError
            res *= 10
            res += ord(ch)-ord('0')
        return res
    

    Only works for base 10 so no bonus points

    reply permalink

  • Anonymous - 10 years, 1 month ago

    C++:

    #include <string>
    #include <iostream>
    #include <cmath>
    
    int parseInt(std::string s) {
        int answer = 0;
        for(unsigned int i = 0; i < s.size(); i++) {
            if((int)s[i] < 48 || (int)s[i] > 57) {
                return 0;
            }
            answer += (((int)s[i] - 48) * pow(10, s.size() - 1 - i));
        }
        return answer;
    }
    
    int main(int argc, char* argv[]) {
        std::cout << parseInt("444") << std::endl;
        std::cout << parseInt("J3110") << std::endl;
    }
    

    reply permalink

  • asheehan - 10 years, 1 month ago

    in Ruby:

    def parse_int(x)
        result = 0
        x = x.lstrip.rstrip
        x.each_byte.with_index do |n,i|
            n -= '0'.unpack('c')[0]
            if n >= 0 and n <= 9
                result += n * 10 ** (x.length - (i+1))
            else # no more numbers, time to return
                if result > 0 or x[0] == '0'.unpack('c')[0]
                    return result / 10 ** (x.length - i)
                else
                    return 'NaN'
                end
            end
        end
    
        return result;
    end
    
    p parse_int('444');
    

    can replace the #unpack with #ord on newer versions of Ruby.

    reply permalink

  • bumbleguppy - 10 years, 1 month ago

    Although deprecated, I will allow octal notation

    function myParseInt(num, radix) {
      var digits = ''; 
      var result = 0;
      var i = 0;
      var decplace = 1;
      var idx = 0;
    
      if (typeof radix === 'undefined') { //optional radix arg
        radix = 10;
      } 
    
      //test first 'num' argument
      if (typeof num !== 'string') { 
        if(typeof num === 'number') {
          if (radix !== 10) {
            num = num.toString(); //maybe someone wants to turn a decimal to binary? Okay...
          } else {
            return num;
          }
        } else {
          return NaN;
        }
      } else {
        num = num.toUpperCase().trim();
      }
    
      //test second 'radix' argument
      if (typeof radix !== 'number' || radix > 36 || radix < 2) { 
        throw new Error('myParseInt : Radix argument only takes integer value from 2 to 36');
      } else{
    
        if (num[0] === '0' && radix === 10) {
          if (num[1] === 'X') {
            radix = 16;
            num = num.substr(2);  //hexadecimal notation
          } else {
            radix = 8;
            num = num.substr(1); //ocatal notation
          }
        }
      }
    
      //chop string that will be used to match the characters in the first argument to the length 'radix'
      digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'.substr(0, radix);
    
      i = num.length;
    
      while(i--) {
        idx = digits.indexOf(num[i]);
        if (idx === -1) {
          return NaN;
        } else {
          result += (decplace * idx);
          decplace *= radix;
        }
      }
    
      return result;
    }
    console.log(myParseInt('0xFF'));
    

    reply permalink

Content curated by @MaxBurstein