Expedia Interview Question
Software Engineer / Developers#include <iostream>
void my_atoi(char str[], int& output)
{
int res = 0;
int i = 0;
int length = strlen(str);
bool is_negative = false;
while (i < length)
{
if (str[i] == ' ')
{
++i;
continue;
}
if (str[i] == '-')
{
++i;
is_negative = true;
}
break;
}
int j = length - 1;
while (j > 0)
{
if (str[j] == ' ')
{
--length;
--j;
}
else
break;
}
while (i < length)
{
if (str[i] <= '9' && str[i] >= '0')
{
int temp_res;
temp_res = res * 10 + str[i] - '0';
if ((temp_res + '0' - str[i]) / 10 != res)
{
std::cout << "Overflow!";
break;
}
else
{
res = temp_res;
}
}
else
{
std::cout << "Invalid input!";
break;
}
++i;
}
if (is_negative)
output = -1 * res;
else
output = res;
}
int main()
{
int res;
my_atoi(" -345 ", res);
return 0;
}
char* s="-99909zsddfasd";
- ST May 10, 2011int num=0,flag=0;
for(int i=0;i<=strlen(s);i++)
{
if(s[i] >= '0' && s[i] <= '9')
num = num * 10 + s[i] -'0';
else if(s[0] == '-' && i==0)
flag =1;
else
break;
}
if(flag == 1)
num = num * -1;
printf("%d",num);