I’m wondering, what’s the origin of asking interviewees to manually parse a string as an int? (without relying on any casting/type-conversion that may be built into the language). Is this a standard question, suggested from a book or list or something?
Has anybody else here on SO gotten asked this particular question during an interview? I guess I nailed it when explaining it and scribbling it on the white board, as I have received a tentative job offer 🙂
Below is my fleshed out implementation in Javascript. There are some naive facets (e.g. it doesn’t take a radix argument) to the following but it demonstrates a (more or less) correct algorithm.
function to_i(strValue) { //named so as to not be confused with parseInt
if (typeof strValue !== 'string' || strValue.length === 0) {
return Number.NaN;
}
var tmpStr = strValue;
var intValue = 0;
var mult = 1;
for (var pos=tmpStr.length-1; pos>=0; pos--) {
var charCode = tmpStr.charCodeAt(pos);
if (charCode < 48 || charCode > 57) {
return Number.NaN;
}
intValue += mult * Math.abs(48-charCode);
tmpStr = tmpStr.substr(0, tmpStr.length-1);
mult *= 10;
}
return intValue;
}
Based on the anecdotal evidence from other answers, I will answer this myself, and accept same: this does not seem to be a “canned” interview question.