題目傳送門
鏈接:https://leetcode-cn.com/problems/string-to-integer-atoi/
題干

題解
看到了題解用python正則運算式可以一行解決QAQ
下面的代碼是C語言的暴力做法
Code
class Solution {
public:
int myAtoi(string s) {
long long res = 0;
bool start = false;
int sign = 1; // 符號位
for (char c : s) {
// 開始記錄
if (start == false) {
if (c == '-') {
sign = -1;
start = true;
} else if (c == '+') {
sign = 1;
start = true;
} else if (isdigit(c)) {
start = true;
res = sign * (c - '0');
} else if (c != ' '){
return 0;
}
} else {
if (isdigit(c)) {
res = res * 10 + sign * (c - '0');
if (res > INT_MAX)
return INT_MAX;
else if (res < INT_MIN)
return INT_MIN;
} else {
break;
}
}
}
return res;
}
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/386972.html
標籤:其他
下一篇:Wordpress搭建(初學者)
