Amazon Interview Question for Software Developers


Country: United States
Interview Type: Phone Interview




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

public static int ParseInt(string number)
{
	bool isNeg = (number[0] == '-');

	int result = 0;
	for(int i = isNeg?1:0; i < number.Length; i++)
	{
		int c = number[0] - '0';

		if(c > 9 || c < 0)
		{
			throw new ArgumentException("Not a valid number");
		}

		result = result*10 + c;
	}
	
	if(isNeg)
	{
		result *= -1;
	}

	return result;
}

- Nelson Perez July 01, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

Code looks good but it does not handle, Integer max and min value cases,
Suppose in C# int max value is 2147483647, suppose if i give "2147483648" it fails.

- kdirishkumar July 01, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

#include <stdio.h>

int main(int argc, char* argv)
{
int a=0;
char* str=(char*)malloc(sizeof(100));
printf("\nEnter the String for integer conversion\n");
gets(str);
printf("\nInput provided::%s\n", str);

printf("\nThe interger output after conversion is::%d\n", strToInt(str));
getch(a);
}
int strToInt(char* str)
{
int result =0,i;
char c='0';
char h='9';

while(*str)
{
printf("\n*str=%c\n", *str);
printf("\n*str=%d\n", *str);

if(*str<c || *str>h)
{
printf("Invalid input\n");
break;
}
i=*str - c;
result=result*10+i;

str++;
}
return result;
}

- Kaushik Roy July 05, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@ kdirishkumar Thanks for the comment well I did not care about overflow case I'm assuming is an integer as it is int.Parse() not a long or someother type of large integer.

To fix thisI'll probaly need to wrap the possible overflow exception to throw my own ArgumentOutOfRangeException.

- Nelson Perez July 08, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Parse the given string from the end, character by character.
Here's a small snippet:

int res = 0;
int factor = 1;

for(int i = givenString.length()-1; i>=0; i--)
{
res = res + givenString.charAt(i)*factor;
factor = factor*10;
}

We have our integer we need.

The time complexity would be O(n).
'n' being the number of characters in the string.

- teli.vaibhav July 01, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

small correction
it should be input.charAt(i)-'0'

- akh July 01, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

convert it into a char array
then

sign=1;
cumulative=0;
BASE=10;
for (int i=0; arr[i] != '\0'; i++)  //loop from front until NUL terminator
{
	// take care of any preceding signs
	if (arr[i]=='+') continue;
	if (arr[i]=='-' ) { sign = -1; continue; }

	// shift over previous sum by a digit (i.e., multiple by base) 
	// and current digit to said sum
	cumulative = (arr[i]-'0') + cumulative*BASE;
}

return sign*cumulative;

- RecruitingForSandvineCanada July 01, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

We can use ASCII values(int) of the characters of the string to Parse it to an Integer.Below is the code for my implementation :

#include<string.h>
#include<stdio.h>
#include<math.h>
int canStringBeParsed(char*);
int parseInt(char*);
main(){
	char *str;
	int stringLength;
	int parsedInt;
	printf("Enter String Length: ");
	scanf("%d", &stringLength);
	str = (char*)malloc(stringLength*sizeof(char));
	printf("Enter the String: ");
	fflush(stdin);
	gets(str);
	if(canStringBeParsed(str)){//Handling Program when given String can't be parsed to Integer
		parsedInt = parseInt(str);
		printf("The Parsed Integer is: %d", parsedInt);
	}
	else{
		printf("The given String can't be parsed to Integer");
	}
}
int canStringBeParsed(char *str){
	int i;
	int len = strlen(str);
	for(i=0; i<len; i++){
		if(str[i] < 48 || str[i] > 57){
			return 0;
		}
	}
	return 1;
}
int parseInt(char *str){
	int i, len, parsedInt=0;
	len = strlen(str);
	char charInt;
	
	for(i=0; i<len; i++){
		charInt = str[len-1-i];
		parsedInt = parsedInt + pow(10, i)*(charInt-48);//Subtract 48 to convert (48-57) to (0-9)
	}
	return parsedInt;
}

- sanskarid94 July 01, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
2
of 2 votes

----SOME MODIFICATION IN MY CODE----
A function

canStringBeParsed(char*)

can be added to check whether the given string can be parse to integer or not.So below is the final code :

#include<string.h>
#include<stdio.h>
#include<math.h>
int canStringBeParsed(char*);
int parseInt(char*);
main(){
	char *str;
	int stringLength;
	int parsedInt;
	printf("Enter String Length: ");
	scanf("%d", &stringLength);
	str = (char*)malloc(stringLength*sizeof(char));
	printf("Enter the String: ");
	fflush(stdin);
	gets(str);
	if(canStringBeParsed(str)){//Handling Program when given String can't be parsed to Integer
		parsedInt = parseInt(str);
		printf("The Parsed Integer is: %d", parsedInt);
	}
	else{
		printf("The given String can't be parsed to Integer");
	}
}
int canStringBeParsed(char *str){
	int i;
	int len = strlen(str);
	for(i=0; i<len; i++){
		if(str[i] < 48 || str[i] > 57){
			return 0;
		}
	}
	return 1;
}
int parseInt(char *str){
	int i, len, parsedInt=0;
	len = strlen(str);
	char charInt;
	
	for(i=0; i<len; i++){
		charInt = str[len-1-i];
		parsedInt = parsedInt + pow(10, i)*(charInt-48);//Subtract 48 to convert (48-57) to (0-9)
	}
	return parsedInt;
}

- sanskarid94 July 01, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void parseInt(String intValue){
char[] chArry = intValue.toCharArray();
int sum = 0;
for(int i=0;i<chArry.length;i++){

int multiplyer = 1;
for(int j=chArry.length-i-1;j>0;j--){
multiplyer = multiplyer * 10;
}
sum = sum + (intValFun(chArry[i])* multiplyer);
}
System.out.println(sum);
}


public static int intValFun(char c){
int val = 0;
switch(c){
case '1':
val = 1;
break;
case '2':
val = 2;
break;
case '3':
val = 3;
break;
case '4':
val = 4;
break;
case '5':
val = 5;
break;
case '6':
val = 6;
break;
case '7':
val = 7;
break;
case '8':
val = 8;
break;
case '9':
val = 9;
break;
default:
val = 0;
break;

}
return val;
}

- Anonymous July 01, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.*;

class printNos
{
static Hashtable vals = new Hashtable();

public static int Conv(String n)
{ 
   for(int i=0; i<10; i++)
   {
    vals.put(i+"",i);
   }

 char[] num = n.toCharArray();
 int val = 0;
 int exp = num.length -1;
 for(int i=0;i<num.length;i++)
 {
  val += (int)vals.get(num[i]+"") * (int)Math.pow(10, exp);
 
  exp--;
 }
 return val;
}
 public static void main(String args[])
 { 
   
   System.out.println(Conv("1204"));
   
 }

}

- liju.leelives July 01, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

{public static int convertStringToInt(String str){
    
    int length = str.length();
    int exp = 0;
    int value = 0;
    for(int i= length-1; i>= 0; i--){
      System.out.println(Math.pow(10,exp));
      System.out.println(str.charAt(i));
      System.out.println(new Integer(str.charAt(i) -48 ));
      value += (Math.pow(10,exp)) * (new Integer(str.charAt(i)) -48 );
      System.out.println(value);
      exp++;
    }
    
    return value;

}}

- JavaBuddy July 01, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

{public static int convertStringToInt(String str){
    
    int length = str.length();
    int exp = 0;
    int value = 0;
    for(int i= length-1; i>= 0; i--){
      System.out.println(Math.pow(10,exp));
      System.out.println(str.charAt(i));
      System.out.println(new Integer(str.charAt(i) -48 ));
      value += (Math.pow(10,exp)) * (new Integer(str.charAt(i)) -48 );
      System.out.println(value);
      exp++;
    }
    
    return value;

}}

- JavaBuddy July 01, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package prac;

import java.util.Scanner;

public class StringToInt {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
char[] charArr = input.toCharArray();
char[] reversedArr = reverse(charArr);
int multiplier = 1;
int num=0;
if(reversedArr==null){
System.out.println("string is invalid, can not be converted to int");
return;
}
for(int i=0;i<reversedArr.length;i++){
num = Character.getNumericValue(reversedArr[i])*multiplier + num;
multiplier = multiplier*10;
}
System.out.println(num);
}
private static char[] reverse(char[] charArr){
int len = charArr.length;
char[]reversedArr = new char[charArr.length];
int j=0;
for(int i=len-1;i>=0;i--){
int numericVal = (int)charArr[i];
if(charArr[i]==' '|| !(numericVal>=48 && numericVal<=57)){
return null;
}
reversedArr[j]=charArr[i];
j++;
}
return reversedArr;
}
}

- Deepak July 03, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <stdio.h>

int main(int argc, char* argv)
{
int a=0;
char* str=(char*)malloc(sizeof(100));
printf("\nEnter the String for integer conversion\n");
gets(str);
printf("\nInput provided::%s\n", str);

printf("\nThe interger output after conversion is::%d\n", strToInt(str));
getch(a);
}
int strToInt(char* str)
{
int result =0,i;
char c='0';
char h='9';

while(*str)
{
printf("\n*str=%c\n", *str);
printf("\n*str=%d\n", *str);

if(*str<c || *str>h)
{
printf("Invalid input\n");
break;
}
i=*str - c;
result=result*10+i;

str++;
}
return result;
}

- Kaushik Roy July 05, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<iostream>

int main() {

    std::string s= "123";
    int num = 0;
    int mul = 1;
    for (int i = s.size()- 1; i >= 0 ; i-- ){
        num += mul * ((int)s[i] - (int)'0');
        mul *= 10;
     }
    std::cout << num;
}

- LKB July 06, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.Scanner;

public class ParseInteger {
	public int parse(String input) {
		int out = 0;
		int p = 1;
		boolean isNeg = input.charAt(0) == '-';

		for (int index = input.length() - 1; index > 0; index--) {

			int c = input.charAt(index) - '0';
			if (c > 9 || c < 0) {

				System.out.println(" java.lang.NumberFormatException: For input string: " + input + "");
				break;
			}

			out += c * p;
			p *= 10;

		}
		if (isNeg) {
			out *= -1;
		} else {
			int val = input.charAt(0) - '0';
			out += val * p;
		}
		return out;
	}

	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		String input = s.nextLine();
		s.close();
		ParseInteger pi = new ParseInteger();
		int output = pi.parse(input);
		System.out.println(output);
	}

}

- garimaprasad1991 January 13, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package test;

public class AmazonParseInt {

	public static void main(String[] args) {
		
		String strInput = new String (""+2356789);

		process (strInput);
		
	}
	
	public static void process (String str){
		
		int resultado = 0, maxDigits;
		int aux = 1;
		int auxMultiply = aux;
		
		for (int index=0; index<str.length(); index++){
			
			aux = aux * 10;
			
		}
		
		resultado = aux;
		maxDigits= aux;
		
		for (int index=0; index<str.length(); index++){
			
			aux = aux / 10;
			auxMultiply = (Integer.valueOf(str.substring(index, index+1)) ) *aux;
			
			resultado = resultado + auxMultiply ;
			
		}
		
		resultado = resultado -maxDigits  ;
			
		
		System.out.println(resultado);
		
		
	}
	

}

- israAzul June 23, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Wow, thanks!

- Emma Neales February 04, 2022 | 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