Amazon Interview Question
Software Engineer / DevelopersThe code has a bug. It fails to detect overflow in certain situation.
For example, when the input is "14316557660" (greater than 2^31-1), the function should print "buffer overflow", but it returns 1431655772.
Should be something like this:
public class ATOI
{
public static void main(String[] args){
String s = "ABCD";
char[] chars = s.toCharArray();
for(int i=0; i<s.length();i++){
int j = (int)chars[i];
System.out.print(" " + j);
System.out.println();
}
}
}
There are couple of things that we need to take care while implementing atoi
1. The number system in which conversion is expected.
2. Its not only a matter of printing the digits. We need to get the integer corresponding to the given string.
e.g. string is: "12345678" then the corresponding integer value is 12345678. We cant just print and go away as above.
3. We need to take care of overflow.
int atoi(char* str){
assert(str!=NULL);//check for null string
bool negFlag=false;
int i=0;
if(str[0]=='-')//check for negative numbers
{negFlag=true;
i++;
}
int num=0;
while(str[i]!='\0'){
num*=10;
num+=(str[i]-'0');//extract value of number at position i
i++;
}
if(negFlag){
num*=-1;
}
return num;
}
In C#
private static string MyItoA(int input)
{
string result = string.Empty;
var quotient = input;
while (quotient > 0)
{
var remainder = quotient % 10;
quotient = quotient / 10;
char addedNumberString = (char)(remainder + (int)'0'); ;
result = string.Concat(addedNumberString , result);
}
return result;
}
And here is my itoa function. it issues malloc a single time at the expense of looping an extra log10(n) times to get the number of digits. if anyone has a more elegant solution please share.
#include <stdio.h>
#include <stdlib.h>
char *itoa(int input) {
int digits = 0;
int value = input;
char *str_val = NULL;
char *end;
if (value == 0) { /* special case */
str_val = malloc(2*sizeof(char));
*str_val = '0';
*(++str_val) = '\0';
return --str_val;
}
if (value < 0) { /* negative value requires an extra digit */
digits++;
}
while (value != 0) {
value /= 10;
digits++;
}
value = input; /* reset value */
str_val = malloc((digits+1)*sizeof(char));
end = str_val + digits;
if (value < 0) { /* allocate negative character */
*str_val = '-';
value = value * -1;
}
*end = '\0';
end--;
while (value != 0) {
*end = '0'+(value % 10);
value /= 10;
end--;
}
return str_val;
}
here it is in C. it handles leading whitespaces & trailing whitespaces. if characters are found in between numbers, it ignores them. it allows negative numbers, and it detects buffer overflows.
- nugarp February 26, 2011