Today's Problem of the Day is to reimplement a classic function, atoi. Atoi takes in one parameter, a string, and returns an int version of that string. So when passed the string "10" atoi will return 10. If the string can't be converted to an int just return 0 or throw an error.
Comments:
Anonymous - 10 years, 4 months ago
In Ruby this is trivial:
def atoi(an_object) an_object.to_i end
reply permalink
David - 10 years, 4 months ago
An Atoi by any other name is still Atoi.
reply permalink
Dustin S. - 10 years, 4 months ago
I wrote this in Java, but, this could be a general language implementation. Sorry the indentation is weird.
private static final int ASCII_ZERO = 48; public int atoi(String s) throws Exception { if (s == null) { throw new NullPointerException("String can't be null."); } int total = 0; int s_len = s.length(); for (int i = s_len - 1; i >= 0; i--) { int c = s.charAt(i); double power = Math.pow(10, s_len - 1 - i); if (c == ASCII_ZERO) { continue; } else if (c > ASCII_ZERO && c <= (ASCII_ZERO + 9) { total += (power * (c - ASCII_ZERO)); } else { throw new Exception("Invalid character."); } } return total; }
reply permalink
Dustin S. - 10 years, 4 months ago
Sorry, I should have put
double power = Math.pow(10, s_len -1 - i);
in the else-if block.reply permalink
bumbleguppy - 10 years, 4 months ago
javascript also has the native parseInt() function, but here's my effort:
function parseIntRedeaux(input_string){ var resultInt = 0; var digitString = '0123456789'; var digit = 0; var power = 1; var i = 0; if(typeof input_string === 'string' && input_string.length > 0){ i = input_string.length; while(i--){ digit = digitString.indexOf(input_string.charAt(i)); if(digit > -1){ resultInt += (digit * power); }else{ throw new Error('Input contains non-numerical characters'); } power *= 10; } return resultInt; }else{ throw new Error('Input must be string of non-zero length'); } } console.log(parseIntRedeaux('a1234'));
reply permalink
Aaron Frase - 10 years, 4 months ago
Here's my implementation in python without using int().
def atoi(n): num_con = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} try: s_len = len(n) ret = 0 for x in n: ret += num_con[x] * 10 ** (s_len - 1) s_len -= 1 return ret except: return 0
reply permalink