Amazon Interview Question for Software Engineer / Developers






Comment hidden because of low score. Click to expand.
4
of 4 vote

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.

#include <stdio.h>

int my_atoi(char *string) {
  
  int negative = 0;
  int value = 0;
  char *start;

  if (string == NULL) /* if data passed in is null */
    return 0;

  start = string;

  while(*start == ' ') /* ignore pre-whitespaces */
    start++;

  if (*start == '-') { 
    negative = 1;
    start++;
  }

  while (*start != '\0') {
    if (*start >= '0' && *start <= '9') { /* numeric characters */
      if (negative == 0 && value * 10 + ((int)*start - '0') < value) { /* check for + buffer overflow */
        printf("buffer overflow \n");
        return 0;
      }
      if (negative == 1 && (((-value) * 10) - ((int)*start - '0') > -value)) { /* check for - buffer overflow */
        printf("buffer overflow \n");
        return 0;
      }
      value = value * 10 + ((int)*start - '0');
    }

    start++;
  }

  if (negative)
    value = -value;

  return value;
}

- nugarp February 26, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

The 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.

- Anonymous January 03, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

really, why cant we use simple sscanf, why cant we use below code, please comment

int main_atoi()
{
	char str[] = "             1234         ";
	int x;
	sscanf_s(str,"%d",&x);
	cout << "x is " << x;
	return 0;
}

- Sirius April 29, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

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();
                }
        }
}

- Anonymous February 24, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

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.

- Tulley February 24, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

atoi is simple to implement. I was asked itoa by Amazon.. :(

- johnny February 24, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Just one line code ... !!!

/*
int num=123;
char dest[10];
*/

sprintf(dest,"%d",num);

- amitp49 June 28, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

atoi is simple to implement. I was asked itoa by Amazon.. :(

- johnny February 24, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

@Johnny
Does it looks gud..

char * myitoa(int num)
{

int temp = num, dig =0, i;

char *str = NULL;

while (temp)
{
temp /= 10;
dig++;

}

str = malloc(dig + 1);
str[dig] = '\0';
while (num)
{
str[dig--] = num%10;
num /=10;
}
return str;
}

- Mike February 24, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

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;
}

- Working February 24, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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;
}

- Jeeper February 25, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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;

}

- nugarp February 26, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

value = value * -1; can be ignored near the end. i had it when my last while loop was value > 0 instead of value != 0. it is unnecessary now.

- Anonymous February 26, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

would not it be better to get the malloc of word length first and then doing the needful conversion and then realloc to squeeze in case extra memory has been allocated. This will avoid the loop to count the digits before actually doing the conversion.

- Ashish May 21, 2012 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More