I am implementing atoi()
by traversing a string from the beginning as well as from the end. Is there anything I can improve?
using namespace std;
int atoiLefttoRight(char *s){
int num = 0;
int negative = 1;
if(s)
{
if(*s == '-')
{
negative = -1;
s++;
}
while(*s && (*s <= '9') && (*s >= '0'))
{
num = (num * 10) + (*s - '0');
s++;
}
}
return (negative * num);
}
int atoiRighttoLeft(char *s){
int i = 1;
int num = 0;
int negative = 1;
if(s){
if(*s == '-')
{
negative = -1;
s++;
}
char *temp = s;
while(*temp)
temp++;
temp--;
while(*temp && temp >= s)
{
if( *temp <= '9' && *temp >= '0'){
num = num + ( (*temp - '0') * i);
i = i*10;
temp--;
}
else
{
temp--;
num = 0;
i = 1;
}
}
}
return (negative * num);
}
int main()
{
cout<<atoiLefttoRight("-12ab3")<<"\n";
cout<<atoiRighttoLeft("1234h5")<<"\n";
}