Last Updated on 2022-01-14 by Clay
題目
Implement atoi which converts a string to an integer.
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned.
Note:
Only the space character ' ' is considered a whitespace character.
Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]. If the numerical value is out of the range of representable values, 2^31 − 1 or −2^31 is returned.
Example:
Input: str = "42"
Output: 42
Input: str = " -42"
Output: -42
Input: str = "4193 with words"
Output: 4193
Input: str = "words and 987"
Output: 0
Input: str = "-91283472332"
Output: -2147483648
本題要實作 atoi() 這一函式,也即是題目給定一組字串輸入,我們要將其可能轉換成整數字串部分提取出來並回傳該整數。
- 若是字串先碰到文字,則回傳 0
- 若是該整數 > 2^31 -1 或整數 < -2^31,則回傳整數型態限制的最大值或最小值
解題思路
這一題我同樣沒有想出什麼特別精妙的解決方法,單純遍歷過字串並設定條件判斷幾種不同的情況,即取得了超過平均的執行時間。
簡單的步驟記錄如下:
- 遍歷字串,判斷碰到的第一個字元是否為 +、-、數值
- 若為空白則跳過,繼續遍歷
- 若不為 +、-、數值,則回傳 0
- 第一個字元判斷過以後,若不為數值則中斷遍歷,開始轉成整數型態
C++ 程式碼
class Solution {
public:
int myAtoi(string s) {
// Init
long ans = 0;
int sign = 0;
string nums;
unordered_map<char, int> c2i({
{'0', 0},
{'1', 1},
{'2', 2},
{'3', 3},
{'4', 4},
{'5', 5},
{'6', 6},
{'7', 7},
{'8', 8},
{'9', 9},
});
// Run
for (int i=0; i<s.size(); ++i) {
if (sign == 0) {
if (s[i] == '+') sign = 1;
else if (s[i] == '-') sign = -1;
else if (isdigit(s[i])) {
sign = 1;
nums += s[i];
}
else if (s[i] == ' ') continue;
else return 0;
}
else {
if (isdigit(s[i])) {
nums += s[i];
}
else break;
}
}
// Convert to numbers
for (int i=0; i<nums.size(); ++i) {
ans = ans * 10 + sign * c2i[nums[i]];
if (ans > INT_MAX) return INT_MAX;
else if (ans < INT_MIN) return INT_MIN;
}
// Return
return ans;
}
};
Python 程式碼
class Solution:
def myAtoi(self, s: str) -> int:
# Init
ans = 0
sign = 0
nums = ""
INT_MAX = pow(2, 31) - 1
INT_MIN = pow(-2, 31)
c2i = {
'0': 0,
'1': 1,
'2': 2,
'3': 3,
'4': 4,
'5': 5,
'6': 6,
'7': 7,
'8': 8,
'9': 9,
}
# Run
for w in s:
if sign == 0:
if w == "+": sign = 1
elif w == "-": sign = -1
elif w.isdigit():
sign = 1
nums += w
elif (w == " "): continue
else: return 0
else:
if w.isdigit(): nums += w
else: break
# Convert to numbers
for n in nums:
ans = ans * 10 + sign * int(n);
if ans > INT_MAX: return INT_MAX
elif ans < INT_MIN: return INT_MIN
# Return
return ans;