function myParseInt(str: string): number {
let result = NaN;
for (let i = 0; i < str.length; i++) {
const dec: number = str.charCodeAt(i);
if (dec < 48 || dec > 57) break;
if(isNaN(result)) result = 0;
const value = dec - 48;
result = result * 10 + value;
}
return result;
}
function myParseFloat(str: string): number {
let result = NaN;
let isDecimal = false; // 小数点
let decimalIndex = 0; // 小数点第几位
const N = 1000;
for (let i = 0; i < str.length; i++) {
const dec: number = str.charCodeAt(i);
const isPoint = dec === 46;
if (isPoint && isDecimal) {
// 再次遇到小数点直接返回
break;
} else if (isPoint) {
isDecimal = true;
continue;
}
if (dec < 48 || dec > 57) break;
if (isNaN(result)) result = 0;
const value = dec - 48;
if (!isDecimal) {
result = result * 10 + value;
} else {
decimalIndex++;
result = (result * N + (value / 10 ** decimalIndex) * N) / N;
}
}
return result;
}
console.log(myParseInt("12.22")); // 12
console.log(myParseFloat("0.22")); // 0.22