xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

LeetCode String to Integer (atoi) js solution All In One

LeetCode String to Integer (atoi) js solution All In One

8. String to Integer (atoi)

https://leetcode.com/problems/string-to-integer-atoi/

solutions

TDD ✅ 🚀 🚀 🚀 🚀 🚀 🚀

"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2022-03-16
 * @modified
 *
 * @description
 * @description
 * @difficulty Medium
 * @complexity O(n)
 * @time O(n)
 * @augments
 * @example
 * @link https://leetcode.com/problems/string-to-integer-atoi/
 * @link https://leetcode-cn.com/problems/string-to-integer-atoi/
 * @solutions
 *
 * @best_solutions
 *
 */

const log = console.log;


/**
 * @param {string} s
 * @return {number}
 */
// var myAtoi = function(s) {
//   const arr = ['-', '+'];
//   const min = -2147483648;
//   const max = 2147483648 - 1;
//   const str = s.trim();
//   let symbol = 1;
//   if(str.length && str[0] === '-' && str[1].match(/[0-9]/)) {
//     symbol = -1;
//   }
//   let nums = [];
//   for (const[i, char] of [...str].entries()) {
//     if(char.match(/[0-9]/)) {
//       nums.push(char);
//     } else {
//       // 搜索到非数字字符就结束,除了第一个 symbol 外
//       if(i === 0 && !arr.includes(char)) {
//         break;
//       }
//       if(i !== 0) {
//         break;
//       }
//     }
//   }
//   // const num = str.replaceAll(/[^0-9]+/g, '');
//   // const num = str.replaceAll(/\D+/g, '');
//   // const num = str.replace(/\D+/g, '');
//   const num = symbol * parseInt(nums.join(''));
//   if(num < min) {
//     return min;
//   } else if(num > max) {
//     return max;
//   } else if(Number.isNaN(num)) {
//     return 0;
//   } else {
//     return num;
//   }
// };

var myAtoi = function(s) {
  const dict = ['-', '+'];
  const str = s.trim();
  // 1. 长度为零
  if(!str.length) {
    return 0;
  }
  // 2. 长度为 1, 非数字
  if(str.length === 1 && str[0].match(/[0-9]/g) === null) {
    return 0;
  }
  // 3. 长度为 2, 首字符非字典符号且首字符是非数字,但次字符是非数字 或 首字符是字典符号,次字符是非数字
  if(str.length === 2 &&
      (!dict.includes(str[0]) && str[0].match(/[0-9]/) === null && str[1].match(/[0-9]/) === null) ||
      (dict.includes(str[0]) && str[1].match(/[0-9]/) === null)
    ) {
    return 0;
  }
  // 4. 长度为 2+, 首字符是字典符号,且次字符是数字
  let symbol = 1;
  if(str[0] === '-') {
    // 负数
    symbol = -1;
  }
  let nums = [];
  // 5. 遍历,直到找出首个非数字,除了第一个 symbol 外
  for (const[i, char] of [...str].entries()) {
    if(char.match(/[0-9]/)) {
      nums.push(char);
    } else {
      // 6. 首字符非字典符号,是次字符非数字 (.1 / +1)
      if(i === 0 && !dict.includes(str[0])) {
        break;
      }
      if(i > 0) {
        break;
      }
    }
  }
  const num = symbol * parseInt(nums.join(''));
  const min = -2147483648;
  const max = 2147483647;
  if(num < min) {
    return min;
  } else if(num > max) {
    return max;
  } else if(Number.isNaN(num)) {
    return 0;
  } else {
    return num;
  }
};

// -2^31, 2^31 - 1
// -2**31, 2**31 - 1 即 [-2147483648, 2147483648 - 1]

// 测试用例 TDD
const testCases = [
  {
    input: '4193 with words  ',
    result: 4193,
  },
  {
    input: '   -42',
    result: -42,
  },
  {
    input: '-abc2022xyz2050',
    result: 0,
    desc: 'value equal to 0',
  },
  {
    input: '12345657890 bigint',
    result: 2147483647,
    desc: 'max value, 2147483647',
  },
  {
    input: 'words and 987',
    result: 0,
    desc: 'value equal to 0',
  },
  {
    input: '-91283472332',
    result: -2147483648,
    desc: 'min value, -2147483648',
  },
  {
    input: '.1',
    result: 0,
    desc: 'value equal to 0',
  },
  {
    input: '+1',
    result: 1,
    desc: 'value equal to 1',
  },
  {
    input: '1a',
    result: 1,
    desc: 'value equal to 1',
  },
];

for (const [i, testCase] of testCases.entries()) {
  const result = myAtoi(testCase.input);
  log(`test case ${i} result: `, result === testCase.result ? `✅ passed` : `❌ failed`, result);
  // log(`test case ${i} result:\n\t\t`, result === testCase.result ? `passed ✅` : `failed ❌`, result);
  // log(`test case ${i} =`, testCase);
}



优化 ❓


var myAtoi = function(s) {
    // const num = parseInt(s.trim());
    const num = parseInt(s);
    // const limit = 2147483648;
    // const max = limit - 1;
    // const min = -limit;
    const max = 2147483647;
    const min = -2147483648;
    // if (Number.isNaN(num)) {
    //   return 0;
    // } else if (num > max) {
    //   return max;
    // } else if (num < min) {
    //   return min;
    // } else {
    //   return num;
    // }
    if (Number.isNaN(num)) {
      return 0;
    } else if (num > min && num < max) {
      return num;
    } else {
      return num >= max ? max : min;
    }
};

var myAtoi = function(s) {
    const num = parseInt(s);
    const limit = 2147483648;
    if (Number.isNaN(num)) {
      return 0;
    } else if (num > -limit && num < limit - 1) {
      return num;
    } else {
      return num >= limit - 1 ? limit - 1 : -limit;
    }
};

refs



©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2022-03-16 21:52  xgqfrms  阅读(31)  评论(6编辑  收藏  举报