LeetCode每日一练【8】

LeetCode每日一练

String to Integer (atoi)

/*
 * @Author: fox
 * @Date: 2022-04-24 07:10:32
 * @LastEditors: fox
 * @LastEditTime: 2022-04-24 08:39:35
 * @Description: https://leetcode.com/problems/string-to-integer-atoi/
 */

/**
 * @description: 大神写的
 * @param {string} s
 * @return {number}
 */
const minInt = -(2 ** 31)
const maxInt = -minInt - 1

const myAtoi = (s) => {
    let number = parseInt(s)
    number = isNaN(number) ? 0 : number;
    if (number > maxInt) return maxInt;
    else if (number < minInt) return minInt;
    return number;
}

/**
 * @description: 自己写的
 * @param {string} s
 * @return {number}
 */
// const myAtoi = (s) => {
//     let str = s.trimStart(); // 删除前面的空白字符
//     let flag = false; // 判断是否为负数

//     // 1. 判断字符串前面是否有正负号
//     if (str[0] === '-') {
//         flag = true
//         str = str.slice(1)
//     } else if (str[0] === '+') {
//         str = str.slice(1)
//     }

//     // 2. 将字符串中的有效数字截取出来
//     for (let index in str) {
//         if (!Number.isInteger(+str[index]) || str[index] === ' ') {
//             str = str.slice(0, index)
//             break
//         }
//     }

//     // 3. 判断数字的正负性以及范围
//     const res = flag ? -(+str) : (+str)
//     if (res >= maxInt) {
//         return maxInt
//     } else if (res <= minInt) {
//         return minInt
//     }
//     return res
// };

const a = '42';
console.log(myAtoi(a)); // 42

const b = '4193 with words';
console.log(myAtoi(b)); // 4193

const c = '       -42';
console.log(myAtoi(c)); // -42

const d = '-91283472332';
console.log(myAtoi(d)); // -2147483648

const e = '+1'
console.log(myAtoi(e)) // 1

const f = '2147483647'
console.log(myAtoi(f)) // 2147483647

const g = '000122'
console.log(myAtoi(g)) // 122
posted @ 2022-04-24 08:44  白い故雪  阅读(12)  评论(0编辑  收藏  举报