C++
字符型数字减去字符‘0’就能得到对应的数字形式
class Solution {
public:
int myAtoi(string s) {
unsigned long len = s.length();
int index=0;
while(index<len){
if(s[index]!=' ') break;
index++;
if(index==len) return 0;
}
int sign=1;
int res=0;
if(s[index]=='+') index++;
else if(s[index]=='-'){
index++;
sign = -1;
}
while(index<len){
char c = s[index];
if(c<'0'||c>'9') break;
if(res>INT_MAX/10||(res==INT_MAX/10)&&((c-'0')>INT_MAX%10)) return INT_MAX;
if(res<INT_MIN/10||(res==INT_MIN/10)&&((c-'0')>-(INT_MIN%10))) return INT_MIN;
res = res*10 + sign*(c - '0');
index++;
}
return res;
}
};
Python
class Solution:
def myAtoi(self, s: str) -> int:
index, res, sign = 0, 0, 1
while index<len(s) and s[index]==' ':
index=index+1
if len(s)==0 or index==len(s):
return 0
if s[index]=='-':
sign=-1
if s[index]=='+' or s[index]=='-':
index=index+1
while index<len(s) and '0'<= s[index]<='9':
c = int(s[index])
res = res*10 + c*sign
index+=1
if res<= -2**31: return -2**31
elif res >= 2**31-1: return 2**31-1
return res