I was recently asked this question in an interview:
"How could you parse a string of the form '12345' into its integer representation 12345 without using any library functions, and regardless of language?"
I thought of two answers, but the interviewer said there was a third. Here are my two solutions:
Solution 1: Keep a dictionary which maps '1' => 1, '2' => 2, etc. Then parse the string one character at a time, look up the character in your dictionary, and multiply by place value. Sum the results.
Solution 2: Parse the string one character at a time and subtract '0' from each character. This will give you '1' - '0' = 0x1, '2' - '0' = 0x2, etc. Again, multiply by place value and sum the results.
Can anyone think of what a third solution might be?
Thanks.
This is Complete program with all conditions positive, negative without using library
Parse the string in oposite order, use one of the two methods for parsing the single digits, multiply the accumulator by 10 then add the digit to the accumulator.
This way you don't have to calculate the place value. By multiplying the accumulator by ten every time you get the same result.
Keep a dictionary which maps all strings to their integer counterparts, up to some limit? Doesn't maybe make much sense, except that this probably is faster if the upper limit is small, e.g. two or three digits.
I expect this is what the interviewer was after:
This method uses far less operations than the method you outlined.
// java version
//unit test
}