gpt4 book ai didi

javascript - 要求受访者手动将字符串解析为 int 的起源是什么?

转载 作者:数据小太阳 更新时间:2023-10-29 03:48:57 25 4
gpt4 key购买 nike

<分区>

我想知道,要求受访者手动将字符串解析为 int 的起源是什么? (不依赖于语言中可能内置的任何强制转换/类型转换)。这是一个标准问题,是从一本书或 list 或其他东西中建议的吗?

SO 上有没有其他人在面试中被问到这个特定问题?我想我在解释它并在白板上潦草地写下它时把它钉牢了,因为我收到了一份暂定的工作机会:)

下面是我用 Javascript 充实的实现。以下内容有一些幼稚的方面(例如,它不采用基数参数),但它展示了一个(或多或少)正确的算法。

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;
}

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com