# **8-String to Integer(Atoi)**
###### tags: `Medium`
## Question

https://leetcode.com/problems/string-to-integer-atoi/
- 情況大致分成有空格或詞彙在數字前、數字前有兩個以上正負號、和數字後有空格和詞彙、小數型式,其實只要根據規則去寫就能解開
## Solution
1. 空格要忽略
2. 正負號要檢查,但正負號或空格相連都回傳0
3. 數字出現就代表開始,中間有標點符號就是結束,不論後面有無數字再出現
4. 數值一定要在INT_MAX~INT_MIN之間
### C++
```cpp=
class Solution {
public:
int myAtoi(string s) {
long long int num = 0;
int n =0;
int start = 0;
for(int i = 0; i < s.size();i
++){
cout<<s[i];
if(s[i] == ' ')
{
if(start == 1)
{
if(n == 1)
{
return (-1)*num;
}
return num;
}
continue;
}
if(s[i] == '-')
{
if(start == 1)
{
if(n == 1)
{
return (-1)*num;
}
return num;
}
if(s[i+1] > '9' || s[i+1] < '0')
{
return 0;
}
n = 1;
}
else if(s[i] == '+')
{
if(start == 1)
{
if(n == 1)
{
return (-1)*num;
}
return num;
}
if(s[i+1] > '9' || s[i+1] < '0')
{
return 0;
}
n = 0;
}
else if(s[i] <= '9' && s[i] >= '0')
{
start = 1;
num = s[i]-'0' + num*10;
if(num > pow(2,31)-1)
{
if(n == 1)
{
return (-1)*pow(2,31);
}
else
{
return pow(2,31)-1;
}
}
}
else
{
if(start == 1)
{
if(n == 1)
{
return (-1)*num;
}
return num;
}
break;
}
}
if(n == 1)
{
return num*(-1);
}
return num;
}
};
```
### Python
- 正則表達式
```python=
class Solution:
def myAtoi(self, s):
m=re.match(r'\s*([\+\-]?\d+)',s)
if not m: return 0
ans=int(m.group(1))
if ans>2**31-1:
ans=2**31-1
elif ans<-2**31:
ans=-2**31
return ans
```
## Solution
- 大神想法:
```python=
class Solution(object):
def myAtoi(self, s):
"""
:type s: str
:rtype: int
"""
digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
signs = ['+', '-']
negative = False
numeric = False
value = 0
maxInt = 2**31-1
minInt = -2**31
# return for empty strings
if len(s) == 0:
return 0
# skip whitespace
index = 0
while index < len(s) and s[index] == ' ':
index += 1
# determine the sign
if index < len(s) and s[index] in signs:
if s[index] == '-':
negative = True
index += 1
# find the numeric value
trimmed = ""
while index < len(s) and (s[index] in digits):
if not numeric:
value = int(s[index])
numeric = True
else:
value = value*10 + int(s[index])
index += 1
if not numeric:
return 0
if negative:
value = value * -1
if value < minInt:
return minInt
if value > maxInt:
return maxInt
return value
```
## Solution
- programming in C++
```c=
int n = s.size();
int num = 0;
int flg = 0;
int i = 0;
while(i<n && s[i] == ' '){
i++;
}
if(i<n && (s[i] == '+' || s[i] == '-')){
if(s[i] == '-') flg = 1;
i++;
}
if( i<n && s[i] < '0' || s[i] > '9') return 0;
while(i<n && s[i] == '0'){
i++;
}
if(i<n && (s[i] < '0' || s[i] > '9')) return 0;
while(i<n && s[i] >= '0' && s[i] <= '9'){
if(num > INT_MAX/10){
if(flg == 1) return INT_MIN;
return INT_MAX;
}
if(num == INT_MAX/10 && (s[i]-'0') > 7){
if(flg == 1) return INT_MIN;
return INT_MAX;
}
num = num*10 + (s[i]-'0');
i++;
}
if(flg == 1) num *=-1;
return num;
}
```