zoukankan      html  css  js  c++  java
  • js 实现简单的parseInt和parseFloat

    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
    
  • 相关阅读:
    线段树学习笔记
    树状数组学习笔记
    P1816 忠诚 ST表模版
    NOIP 2017 D1T2 时间复杂度
    Ubuntu镜像源
    字符串数据结构模板
    白书的一些奇怪模板
    高精度模板
    大整数类模板
    线段树模板1
  • 原文地址:https://www.cnblogs.com/ajanuw/p/14113139.html
Copyright © 2011-2022 走看看