Amazon Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: In-Person
public static int atoi(String s) {
/* to check null and empty */
if (s == null || s.length() == 0)
return -1;
int i = 0, number = 0;
boolean neg = false, err = false;
/* remove spaces from front and end */
s = s.trim();
/* check for negative sign */
if (s.charAt(i) == '-') {
neg = true;
i++;
}
/* form number */
for (; i < s.length(); i++) {
/* check for invalid chars in between */
if (s.charAt(i) < '0' || s.charAt(i) > '9') {
err = true;
System.err.println("Invalid string");
break;
}
int digit = s.charAt(i) - '0';
number = number*10 + digit;
}
if (err)
return -1;
else if (neg)
return -number;
return number;
}
#include "string.h"
- Bin October 31, 2012#include "stdio.h"
main()
{
char str[]="ac1234e5ABCefabcd";
int slen = strlen(str);
int i;
__int64 shex=0;
//first check whether the string can be converted to INTEGER.
//convert string to integer
for(i=0; i<slen; i++)
{
if(str[i]>='0' && str[i]<='9')
{
shex = shex*16 + (str[i]-'0');
}else if(str[i]>='a' && str[i]<='f')
{
shex = shex*16 + (str[i]-'a'+10);
}else if(str[i]>='A' && str[i]<='F')
{
shex = shex*16 + (str[i]-'A'+10);
}
}
printf("%#llx\n\r", shex); //need to convert double to long
}
issues and questions:
ingore space or not? how to handle '-'?
how to print integer number which is bigger than the max value of __int64