zoukankan      html  css  js  c++  java
  • leetcode 8. String to Integer (atoi)

    这方法的条件有

    1. 前面可以是连续空白,但不能出现字符
    2. 前面有字符返回0
    3. 前面可以有+-
    4. 数字后面的字母会被删掉
    5. 解后的数字如果超出 [Math.pow(-2,31), Math.pow(2,31)-1], 返回这些极限值
      function myAtoi(str) {
          var map = new Array(10).fill(1).reduce((ret, el, index) => {
            ret[index] = 1
            return ret
          }, {})
          map['-'] = 1;
          map['+'] = 1;
          var hasNum = false, ret = ''
          for (var i = 0; i < str.length; i++) {
            var c = str[i]
            if (!hasNum) {
              if (map[c]) {
                ret += c;
                //符合只能匹配一次
                if (c === '+' || c == '-') {
                  delete map['+']
                  delete map['-']
                }
                hasNum = true
              } else {
                if (c == ' ') {
                  continue
                }
                return 0
              }
            } else {
              if (map[c]) { //- + 1
                ret += c;
              } else {
                break
              }
            }
          }
          var parsedString = parseInt(ret);
          if (isNaN(parsedString)) {
            return 0;
          }
          if (parsedString >= Math.pow(2, 31)) {
            return Math.pow(2, 31) - 1;
          }
    
          if (parsedString < Math.pow(-2, 31)) {
            return Math.pow(-2, 31);
          }
    
          return parsedString
        };
    
        console.log(myAtoi('-91283472332'))
    

    或者直接动用正则,将前面的有效字符匹配出来

      function myAtoi(str) {
          var a = str.match(/^s*([+-]?d+)/)
          if (a && a[1]) {
            var num = Number(a[1]);
            if (num < 0) {
              return Math.max(-Math.pow(2, 31), num)
            }
            return Math.min(Math.pow(2, 31) - 1, num)
          } else {
            return 0
          }
        };
    

    JS中还能直接作弊

    var myAtoi = function(str) {
       let parsedString = parseInt(str);
    
       if(parsedString >= Math.pow(2,31)) {
          return Math.pow(2,31) - 1;
       }
    
       if(parsedString < Math.pow(-2,31)) {
          return Math.pow(-2,31);
      }
    
       if(isNaN(parsedString)) {
          return 0;
        }
    
       return parsedString;
    };
    
    
  • 相关阅读:
    ubuntu18.04下eclipse修改maven源为阿里源
    Java中使用队列Queue
    Redis学习笔记——Redis的基本操作
    ubuntu安装redis
    Spring Boot使用监听器Listener
    Spring Boot中在程序中获得application.properties中的值
    Spring Boot使用过滤器Filter
    基于GTID的主从架构异常处理流程
    goroutine与调度器
    使用synergyc共享键鼠
  • 原文地址:https://www.cnblogs.com/rubylouvre/p/12040035.html
Copyright © 2011-2022 走看看