# 8ms C++ solution, easy to understand

• int myAtoi(string str) {
long result = 0;
int indicator = 1;
for(int i = 0; i<str.size();)
{
i = str.find_first_not_of(' ');
if(str[i] == '-' || str[i] == '+')
indicator = (str[i++] == '-')? -1 : 1;
while('0'<= str[i] && str[i] <= '9')
{
result = result*10 + (str[i++]-'0');
if(result*indicator >= INT_MAX) return INT_MAX;
if(result*indicator <= INT_MIN) return INT_MIN;
}
return result*indicator;
}
}

• This is more concise than mine C code. Nice job! Thanks for your share. I'm gonna optimize the way how to calculate the result in my code.
Actually it is needless to judge 'i < str.size()' on Ln 9 of your code because the 'while' procedure will stop immediately once non-numeral appears.

• So concise! You are nice programmer!

• Thanks for your share, it is grate!
But, may I ask you a question.
I used istringstream like this

istringstream ss(str);
int ival(0);
ss >> ival;

It is accept! Is it match the rule?

• Yes,you are right! Thanks for your advice. I have removed it.

• It may be accepted, but i think this problem want you to re-implement the atoi() function, but you just used another function which is similar to it.

• how does the 'while' stop?

• When str[i] does not represent for a number

• great job! I think maybe using

isdigit(str[i])

instead of

'0'<= str[i] && str[i] <= '9'

can be more concise?

• yes, you're right!

• This post is deleted!

• In some machine, long may be same with int, so I think it is better use long long. nice code

• This post is deleted!

• Agreed.

The use of a type of bigger range to detect the overflow is a good idea to keep in mind though.

• in the case of "+-2", your code will be TLE, because the i = str.find_first_not _of(' ');

• Why I copy paste your code, and it takes 12 ms? So weird, will the runtime change?

• For the empty string "", str.find_first_not_of(' ') assigns -1 to i, which results in access to str[-1].

Other than that, great solution!

• the for() is extra

• Thanks for your code! This is my code, and it can work in my own computer, but it can't pass in the leetcode, can you help me? Looking forward to your reply.
class Solution {
public:
int myAtoi(string str) {
int pos =0, num=0, fuhao=1;
if(str[pos] =='+')
pos++;
else if(str[pos]== '-'){
pos++;
fuhao = -1;
}
while(pos < str.length()){
if(str[pos] >='0' && str[pos] <= '9')
num = num*10 +str[pos] - '0';
if(num>=0)
pos++;
}
//num = fuhao;
cout<<num
fuhao<<endl;
}
};

• To pass the case "-+2", you can add another flag for the number of indicator in your code.

int flag = 0;
if(str[i] == '-' || str[i] == '+')
{
indicator = (str[i++] == '-')? -1 : 1;
flag++;
}
if(flag>1)
{
return 0;
}

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.