String to Integer Atoi

    0

    0

    pavan koka

    var a = [1, 2, 'foo', notEqual(a)];

    console.

    var myAtoi = function(s) {
      const ans = [];
      let negation = 1;
      let sign = '';
      let unacceptedChars = false;
      let stopReading = false
    
      s.split('').forEach(el => {
        if(!Number.isInteger(parseInt(el)) && el !== ' ' && el !== '+' && el !== '-' && !ans.length) {
          unacceptedChars = true
        }
        if(sign.length && !Number.isInteger(parseInt(el))) {
          stopReading = true
        }
        if((!Number.isInteger(parseInt(el)) && ans.length)) {
          stopReading = true;
        }
        if(stopReading || unacceptedChars) return
        if(el === '+' || el === '-') {
          sign += el;
          if(el === '-') {
            negation = -1
          }
          if(!ans.length && sign.length > 1) {
            unacceptedChars = true;
          }
        }
        if(el === '.') {
          stopReading = true
        }
        if(Number.isInteger(parseInt(el)) && !stopReading) {
          ans.push(el)
        }
      })
      if(unacceptedChars) {
        return 0
      }
      const result = negation * ans.join('');
    
      if(result > (Math.pow(2,31) - 1)) {
        return (Math.pow(2,31) - 1)
      } else if(result < -1 * Math.pow(2,31)) {
        return -1 * Math.pow(2,31)
      }
    
      return result
    };
    
    function notEqual(arr) {
      let isEqual = true;
      arr.forEach(el => {
        if(el !== arr[0]) isEqual = false
      })
      return isEqual
    }
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.