題目: LeetCode - 8. String to Integer (atoi)

題目說明

定義一個自己的 atoi() 函數。

  • 字串前面的空白需忽視
  • 正負號只看最前面的符號
  • 若超過範圍則回傳最大值或最小值

解題思路

使用 String 的 find_first_not_of() 來去除前面的空白,接著先檢查是否有正負號,之後將數字存入即可。( 這邊使用 long 是為了避免越界 )

參考解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int myAtoi(string str) {
long res = 0;
int indicator = 1, mx = INT_MAX, idx = str.find_first_not_of(' ');
if(idx == -1) return 0;
if(str[idx] == '+' || str[idx] == '-') indicator = str[idx++] == '-' ? -1 : 1;
while(isdigit(str[idx]))
{
res = res * 10 + (str[idx++] - '0');
if(res > mx) return indicator == 1 ? INT_MAX : INT_MIN;
}
return res * indicator;
}
};