实现 atoi
,将字符串转为整数。
这个代码写得太恶心了,等忙完论文一定改改。
python:
class Solution(object):
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
index = 0
res = ""
str = str.lstrip()
l = len(str)
if l==0:
return 0
elif str[index] == "+":
index += 1
while(index<l):
if(ord(str[index])>=48 and ord(str[index])<=57):
res += str[index]
index += 1
else:
break
if res == "":
return 0
elif str[index] == "-":
res += str[index]
index += 1
while(index<l):
if(ord(str[index])>=48 and ord(str[index])<=57):
res += str[index]
index += 1
else:
break
if res == "-":
return 0
elif (ord(str[index])>=48 and ord(str[index])<=57):
while(index<l):
if(ord(str[index])>=48 and ord(str[index])<=57):
res += str[index]
index += 1
else:
break
else:
return 0
result = int(res)
if result>(2**31-1):
return 2**31-1
elif result<-(2**31):
return -(2**31)
return int(res)
C++,我在用string索引时总是报错,我就先将string转成char然后索引比较ASCII,最后用了istringstream转成int。
class Solution {
public:
int myAtoi(string str) {
int start = 0;
int l = str.length();
if(l==0){
return 0;
}
char s[l];
for(int i=0;i<l;i++){
s[i] = str[i];
}
string res = "";
while(s[start]==32){
start += 1;
if(start == l){
return 0;
}
}
if(s[start]==43){
start += 1;
while(start<l){
if(s[start]>=48 && s[start]<=57){
res += str[start];
start += 1;
}
else{
break;
}
}
if(res.length() == 0){
return 0;
}
}
else if(s[start]==45){
res += "-";
start += 1;
while(start<l){
if(s[start]>=48 && s[start]<=57){
res += str[start];
start += 1;
}
else{
break;
}
}
if(res.length() == 1){
return 0;
}
}
else if(s[start]>=48 && s[start]<=57){
res += str[start];
start += 1;
while(start<l){
if(s[start]>=48 && s[start]<=57){
res += str[start];
start += 1;
}
else{
break;
}
}
}
else{
return 0;
}
istringstream ss(res);
int y;
ss >> y;
if(y>INT_MAX){
return INT_MAX;
}
else if(y<INT_MIN){
return INT_MIN;
}
else{
return y;
}
}
};