|
| 1 | +// 方法一:一般解法 |
| 2 | + |
| 3 | +/** |
| 4 | + * 字符串转换整数 (atoi) |
| 5 | + * @param {string} s |
| 6 | + * @return {number} |
| 7 | + */ |
| 8 | +var myAtoi = function (s) { |
| 9 | + let flag = 1; // 1:正数 1-:负数 |
| 10 | + |
| 11 | + s = s.trimStart(); |
| 12 | + |
| 13 | + if (s[0] === "-") { |
| 14 | + flag = -1; |
| 15 | + s = s.slice(1); |
| 16 | + } else if (s[0] === "+") { |
| 17 | + s = s.slice(1); |
| 18 | + } |
| 19 | + |
| 20 | + let arr = []; |
| 21 | + let count = 0; |
| 22 | + |
| 23 | + for (let i = 0; i < s.length; i++) { |
| 24 | + let curr = s[i]; |
| 25 | + |
| 26 | + if (+curr === +curr && count === i && curr !== " ") { |
| 27 | + arr.push(curr); |
| 28 | + count++; |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + let result = arr.length > 0 ? Number(arr.join("")) : 0; |
| 33 | + result *= flag; |
| 34 | + |
| 35 | + const min = -Math.pow(2, 31); |
| 36 | + const max = Math.pow(2, 31) - 1; |
| 37 | + |
| 38 | + if (result < min) { |
| 39 | + result = min; |
| 40 | + } else if (result > max) result = max; |
| 41 | + |
| 42 | + return result; |
| 43 | +}; |
| 44 | + |
| 45 | +// 方法二:有限自动机 (DFA) |
| 46 | + |
| 47 | +/** |
| 48 | + * 字符串转换整数 (atoi) |
| 49 | + * @param {string} s |
| 50 | + * @return {number} |
| 51 | + */ |
| 52 | +var myAtoi = function (s) { |
| 53 | + const am = automaton(); |
| 54 | + |
| 55 | + for (let i = 0; i < s.length; i++) { |
| 56 | + am.get(s[i]); |
| 57 | + } |
| 58 | + |
| 59 | + return am.result() |
| 60 | +}; |
| 61 | + |
| 62 | +const MAX_NUMBER = Math.pow(2, 31) - 1; |
| 63 | +const MIN_NUMBER = -Math.pow(2, 31); |
| 64 | + |
| 65 | +function automaton() { |
| 66 | + let sign = 1, ans = 0, state = "start"; |
| 67 | + let table = { |
| 68 | + start: ["start", "signed", "in_number", "end"], |
| 69 | + signed: ["end", "end", "in_number", "end"], |
| 70 | + in_number: ["end", "end", "in_number", "end"], |
| 71 | + end: ["end", "end", "end", "end"], |
| 72 | + }; |
| 73 | + |
| 74 | + return { |
| 75 | + get(c) { |
| 76 | + state = table[state][this.getCol(c)]; |
| 77 | + |
| 78 | + if (state === "in_number") { |
| 79 | + ans = ans * 10 + Number(c); |
| 80 | + ans = sign === 1 ? Math.min(ans, MAX_NUMBER) : Math.min(ans, -MIN_NUMBER); |
| 81 | + } else if (state === "signed") { |
| 82 | + sign = c === "-" ? -1 : 1; |
| 83 | + } |
| 84 | + }, |
| 85 | + |
| 86 | + getCol(c) { |
| 87 | + if (c == " ") { |
| 88 | + return 0; |
| 89 | + } |
| 90 | + if (c == "+" || c == "-") { |
| 91 | + return 1; |
| 92 | + } |
| 93 | + if (/\d/.test(c)) { |
| 94 | + return 2; |
| 95 | + } |
| 96 | + return 3; |
| 97 | + }, |
| 98 | + |
| 99 | + result() { |
| 100 | + return sign * ans; |
| 101 | + }, |
| 102 | + }; |
| 103 | +} |
0 commit comments