Leetcode - Medium - 8. String to Integer (atoi) - Javascript
Implement the myAtoi(string s)
function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi
function).
The algorithm for myAtoi(string s)
is as follows:
- Read in and ignore any leading whitespace.
- Check if the next character (if not already at the end of the string) is
'-'
or'+'
. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present. - Read in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored.
- Convert these digits into an integer (i.e.
"123" -> 123
,"0032" -> 32
). If no digits were read, then the integer is0
. Change the sign as necessary (from step 2). - If the integer is out of the 32-bit signed integer range
[-231, 231 - 1]
, then clamp the integer so that it remains in the range. Specifically, integers less than-231
should be clamped to-231
, and integers greater than231 - 1
should be clamped to231 - 1
. - Return the integer as the final result.
Note:
- Only the space character
' '
is considered a whitespace character. - Do not ignore any characters other than the leading whitespace or the rest of the string after the digits.
Example 1:
Input: s = "42" Output: 42 Explanation: The underlined characters are what is read in, the caret is the current reader position. Step 1: "42" (no characters read because there is no leading whitespace) ^ Step 2: "42" (no characters read because there is neither a '-' nor '+') ^ Step 3: "42" ("42" is read in) ^ The parsed integer is 42. Since 42 is in the range [-231, 231 - 1], the final result is 42.
解題方向:
1. 一開始以為是單純的文字移除空白和文字後再轉成 int 的函式, 但詳細了解後並非這麼簡單
2. 這邊有分成兩階段共三步驟方式處理
- 第一階段: 累計數字
step 1. 先利用 isPositive 紀錄是否開頭為 '-', '+', '0-9' 如果在這個步驟遇到空白外的文字即立刻回傳 0
step 2. 當紀錄 isPositive 後就開始累計 '0-9', 遇到其他文字立即中斷 while 迴圈, 結束累計
- 第二階段 處理回傳值
step 3. 透過文字個別轉成數字時判斷是否落在 minLimit 與 maxLimit 之間, 如不是即立刻回傳對應的上下限值即可
程式碼 :
/** * @param {string} s * @return {number} */ var myAtoi = function(s) { let index = 0; let isPositive = 0; let resultString = ''; const digiArray = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']; while(index < s.length) { const letter = s[index]; index++; if (isPositive === 0) { if (letter === ' ') { continue; } else if (letter === '-') { isPositive = '-1'; continue; } else if (letter === '+') { isPositive = '1'; continue; } else if (digiArray.includes(letter)) { isPositive = '1'; resultString += letter; } else { return 0; } } else { if (!digiArray.includes(letter)) { break; } else { resultString += letter; } } } const minLimit = -2147483648; const maxLimit = 2147483647; let result = 0; for (let i in resultString) { result = result * 10 + isPositive * parseInt(resultString[i]); if (result < minLimit) { return minLimit}; if (result > maxLimit) { return maxLimit}; } return result; };
執行成果:
0 意見 :
張貼留言