LeetCode C++ String to Integer (atoi) 字串轉整數

今天要練習的 LeetCode 題目是 String to Integer (atoi) 字串轉整數,並且以 C++ 實作出來。

LeetCode 題目

https://leetcode.com/problems/string-to-integer-atoi/
難度:Medium

String to Integer (atoi) 是 LeetCode 題目的第 8 題,

題目是實作一個字串轉整數,有一些需求,

  • 要能夠忽略空白開頭。
  • 能處理 '-', '+' 符號。
  • 如果數字超過 32 bit 長度,則回傳最大數值,大於 2^31-1 回傳 2147483647,小於 -2^31 則回傳 -2147483648。

解題思路

先把字串前面出現的空白都忽略,直到遇到第一個出現的 '-', '+' 符號或數字,然後紀錄正負號,如果是負號開頭的話就在 sign 變數設定為 -1 記錄一下,最後的數字再乘上 sign 即可,接著忽略 0 開頭的數字。

主要邏輯為一個 while 迴圈去使用 isdigit 判斷每個字元是不是數字,該字元是數字的話就將字元減去 '0' 就可以得到數字,然後將該數字再加上之前的 sum * 10,最後整個 while 迴圈會遇到 '\0' 結束字元時 isdigit 會判斷成不是數字進而終止 while 迴圈,最後再將 sum 乘上 sign 變數就可以回傳最終結果。

針對 32 bit 整數邊界進行處理,大於 2147483647 回傳 2147483647,小於 -2147483648 則回傳 -2147483648,另外輸入是超長的數字字串是 long 存不下的話,也會針對 len 長度太長進行邊界處理。

答案

以下為 C++ String to Integer (atoi) 的 solution

cpp-string-to-integer-atoi.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// g++ cpp-string-to-integer-atoi.cpp -o a.out
#include <iostream>
#include <string>
using namespace std;

class Solution {
public:
int myAtoi(string s) {
long sum = 0;
int i = 0;
int sign = 1;

while (isspace(s[i])) { i++; }

if (s[i] == '-') {
sign = -1;
i++;
} else if (s[i] == '+') {
i++;
}

while (s[i] == '0') { i++; }

int len = 0;
while (isdigit(s[i])) {
sum = sum * 10 + s[i] - '0';
i++;
len++;
if (len > 10)
break;
}

sum = sum * sign;
if (sum > 2147483647)
return 2147483647;
else if (sum < -2147483648)
return -2147483648;
else
return sum;
}
};

int main() {
Solution s;
string s1 = "123";
cout << s.myAtoi(s1) << "\n";
string s2 = "0032";
cout << s.myAtoi(s2) << "\n";
string s3 = "4193 with words";
cout << s.myAtoi(s3) << "\n";
string s4 = " -42";
cout << s.myAtoi(s4) << "\n";
string s5 = "-91283472332";
cout << s.myAtoi(s5) << "\n";
string s6 = "+1";
cout << s.myAtoi(s6) << "\n";
string s7 = "20000000000000000000";
cout << s.myAtoi(s7) << "\n";
string s8 = " 0000000000012345678";
cout << s.myAtoi(s8) << "\n";
string s9 = "00000-42a1234";
cout << s.myAtoi(s9) << "\n";
return 0;
}

參考
String to Integer (atoi) - LeetCode
https://leetcode.com/problems/string-to-integer-atoi/
字符串转换整数 (atoi) (String to Integer (atoi)) - 力扣 (LeetCode)
https://leetcode-cn.com/classic/problems/string-to-integer-atoi/description/

其它相關文章推薦
C/C++ 新手入門教學懶人包
LeetCode C++ two sum 兩數之和
LeetCode C++ Range Sum Query - Immutable 區域和檢索