Amazon Interview Question for Software Engineer Interns


Country: United States
Interview Type: Phone Interview




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

Hi
This function should work well. Short and sweet

int num(char* s)
{
char* temp = s;
int len = strlen(s);
int a=0,sum=0;
int i=0;
while(*temp)
{
a = *temp - 48;
a = a * pow(10,len-1-i);
sum = sum + a;
i++;
temp++;
}

return sum;

}

- Bracelet July 01, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Missing a lot boundary cases. It won't work for alphanumeric strings, +123, -123. In case of null or empty strings, it will return 0 which is wrong.

- Adi July 20, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

It should also include conditions to check trailing spaces.

- Moni July 28, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 2 vote

int main(int argc, _TCHAR* argv[])
{


char * str = "586";
int sum = 0;

for (int i = 0; str[i] !='\0'; i++)
{

sum = sum * 10 + (str[i] - '0');

}

cout << sum << endl;
return 0;
}

- Ashok Gowla June 19, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

this will not work for negative numbers.

- kaustubh deshmukh June 19, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

for negative numbers you just need to check the charArray[0]. if it is ' - ' then initialize previously defined variable to -1 and multiply with the result before returning the result.

- sudheerjay June 19, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <stdio.h>
#include <string.h>

int toInt(char *value){

    int ind = 0, sum = 0, multiplier = 0;

	// find the length of value
	// or number of characters present in value
	if ( value[0] == '-' ){
        for(ind=1; value[ind] != '\0'; ind++);
        ind--;
        
        while( ind >= 1 ) {
        
            if(multiplier == 0) {
                sum = (value[ind] - '0' ) ;
                multiplier = 10;
            }
            else{ 
                sum = sum + (multiplier * (value[ind] - '0' ));
                multiplier = multiplier * 10;
            }
            ind--;     
           
	    }  
        return sum*-1;

	}
    else {
	    for(ind=0; value[ind] != '\0'; ind++);
        ind--;
    
	    while( ind >= 0 ) {
        
            if(multiplier == 0) {
                sum = (value[ind] - '0' ) ;
                multiplier = 10;
            }
            else{ 
                sum = sum + (multiplier * (value[ind] - '0' ));
                multiplier = multiplier * 10;
            }
            ind--;       
	    }  
        
        return sum;
    }
	
}



void main() {
   char *value = "6834";
   printf("\n\n %d ", toInt(value)); // gives 6834
   // works for negative numbers as well.. :)
}

- kaustubh deshmukh June 19, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

you just need to implement the atoi() function from c library.

here is the hint:
1) You set the pointer at the start of the char array.
2) And then inside for loop you go over each character and multiply by 10 and add the character by subtracting by 0, and store it in the result.
something like:
/*
int res=0;
 for (int i = 0; str[i] != '\0'; ++i)
        res = res*10 + str[i] - '0';
*/
And if you will try with "26745". the number would be 26745 as well.

and if you need to check for signed values like "-26745"
just check if charArray[0] is ' - '. if so, store it in a variable(eg: int sign= -1 ;) 
then iterate the loop from i=1 and return sign*res;
which will return -26745 for "-26745".

- sudheerjay June 19, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

int toInt(const char* str, bool* result = NULL)
{
int retval = 0;
bool resval = false;

if( str )
{
try
{
std::stringstream s;
s << str;
s >> retval;
resval = true;
}
catch(std::exception& e)
{
e.what();
}
}
if( result )
{
*result = resval;
}

return retval;
}

- BFRazor June 19, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <iostream>
using std::cout;
using std::endl;
using std::string;

int str_to_int(char* str){
return atoi(str);
}

int main(){

string data ="-546";
const char* cData=data.c_str();
cout<<"INT : "<<str_to_int(const_cast<char*>(cData))<<endl;

return 0;
}

- Ishir June 19, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<iostream>
#include<climits>
#include<cstdlib>
#include<cctype>
using namespace std;
int convertStringToInt(char * str,int &a)
{
    if(NULL == str)
    {
        return -1;
    }
    bool isNeg = false;
    char * start = str;
    while(isspace(*start))
    {
        ++start;
    }
    if(*start == '-')
    {
        isNeg = true;
        ++start;
    }
    while(*start)
    {
        if(*start >= '0' && *start <= '9')
        {
            if(!isNeg && a > (INT_MAX - (int)*start + '0')/10)
                {
                    cout<<"overflow"<<endl;
                    return -1;
                }
            if(isNeg && a > ((abs(INT_MIN)) - (int)*start + '0')/10)
                {
                    cout<<"underflow"<<endl;
                    return -1;
                }
                 a = a*10 + (int)*start - '0';
        }
        ++start;
    }
    if(isNeg)
    {
        a = -1*a;
    }
    return 0;
}
int main()
{
    int a =0;
    char str[] = "  214748hh";
    int result = convertStringToInt(str,a);
    if(result == 0)
    {
        cout<<"Value: "<<a<<endl;
    }
    return 0;

}

- Dexter June 19, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Best way to do that

long long stringToInt(char *s){
int i=0,flag  = 1;
lon long x = 0;
int l = (int)strlen(s);
if(s[0] == '-' ){ flag  = -1; i++;}
	for(;i<l;++i){
	x = (x<<3) + (x<<1) + s[i]-'0';
	}
   return (flag)*(x);
}

- Advaita11 June 28, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

// practicebrainbench.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <string>
#include <cctype>
#include <regex>
using namespace std;

int find(char* str)
{
char* s = str;
int count[123];
int counter=0;
for(int i=0;i<123;i++) count[i] = 0;

while( *s != '\0')
{
if(count[*s] == 0)
{
count[*s]++;
s++;
counter++;
}
else
{
return counter;
}
}

return 0;

}
int count( int S[], int m, int n )
{
// If n is 0 then there is 1 solution (do not include any coin)
if (n == 0)
return 1;

// If n is less than 0 then no solution exists
if (n < 0)
return 0;

// If there are no coins and n is greater than 0, then no solution exist
if (m <=0 && n >= 1)
return 0;

// count is sum of solutions (i) including S[m-1] (ii) excluding S[m-1]
return count( S, m - 1, n ) + count( S, m, n-S[m-1] );
}
template<class T>
T getmax(T a,T b)
{
T result;
result = (a>b)?a:b;
return result;
}

class A
{
int i;
char* s;
public:

A( int j):i(j)
{
s = new char(10);
strcpy(s,"Keyur");
}
A()
{
s = new char(10);
strcpy(s,"Keyur");
}

virtual void fun() { cout<<"A func"<<endl; }
void print()
{
cout<<&i<<endl;;
cout<<&s<<endl;;

}
A operator + (const A& rhs)
{
A obj;
obj.i = i + rhs.i;
return obj;

}
A(const A& obj)
{
i = obj.i;
s = new char(strlen(obj.s) + 1);
strcpy(s,obj.s);

}
A& operator = (const A& obj)
{
if( &obj != this)
{
i = obj.i;
delete []s;
s = new char(strlen(obj.s) + 1);
strcpy(s,obj.s);
return *this;
}

}

};



int getnum(int a[],int n)
{
int max=0;

for(int i=0;i<n;i++)
{

if (a[i] > max )
max = a[i];
}

return max;
}

int num(char* s)
{
char* temp = s;
int len = strlen(s);
int a=0,sum=0;
int i=0;
while(*temp)
{
a = *temp - 48;
a = a * pow(10,len-1-i);
sum = sum + a;
i++;
temp++;
}

return sum;

}
int main()
{
char* s ="10000001";;
cout<<num(s);

getchar();
return 0;
}

- Keyur Patel July 01, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

In C#, just to change things up. Works with negative

public static int ToInt(string str)
        {
            int result = 0;
            char[] cArr = str.ToCharArray();

            // account for negative
            int end = cArr[0] == '-' ? 1 : 0;

            for (int i = str.Length - 1, j = 1; i >= end; i--, j *= 10)
            {
                int digit = ToInt(cArr[i]);
                result += digit * j;
            }

            if (end == 1)
                result *= -1;
            return result;
        }

        public static int ToInt(char c)
        {
            return (int)c - 48;
        }

- joey January 24, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

str = str.trim();
int i = 0;
int n = str.length();
int sign = 1;
while(i<n && str.charAt(i)=='+'){
	i++;
}
while(i<n && str.charAt(i)=='-'){
	sign==-1;
	i++;
}
int ans = 0;
while(i<n && Character.isDigit(str.charAt(i))){
	int digit = Character.getNumericValue(str.charAt(i));
	if(ans>Integer.MAX_VALUE/10 || (ans>Integer.MAX_VALUE/10 && digit>7)){
		return sign==1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
	}
	ans = ans*10 + digit;
	i++;
}
return sign* ans;

- wadephz February 04, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

// Program needs to be modified for all digits 0-9
public static void main(String[] args)
{
String str = "586";
HashMap<Character, Integer> hm = new HashMap<Character, Integer>();
hm.put('5',5);
hm.put('8',8);
hm.put('6',6);
int sum = 0 ;
int sign = 1;
for(int i = 0 ; i<str.length() ; i++){
if(str.charAt(i) == '-'){
sign = -1;
continue;
}
int x = hm.get(str.charAt(i));
sum += (x * Math.pow(10,(str.length() - i - 1)));
}
System.out.println(sum*sign);
}

- Anonymous February 13, 2016 | 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