Amazon Interview Question for SDE1s


Team: Kindle
Country: India
Interview Type: Written Test




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

def get_float(a)
  a_prefix = 0
  a_suffix = 0
  pre = true
  decimals = 0
  a.each do |c|
    if c!='.' and pre
      a_prefix = a_prefix*10+ c.to_i	
    elsif c=='.'
      pre = false
    else
      a_suffix = a_suffix*10+c.to_i
      decimals+=1
    end
  end
  return a_prefix+(a_suffix*(1.0/10.0**decimals)) 
end

return (float(a)+float(b)) # assuming a and b are input char arrays

}

- kiruba May 10, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def get_float(a)
  a_prefix = 0
  a_suffix = 0
  pre = true
  decimals = 0
  a.each do |c|
    if c!='.' and pre
      a_prefix = a_prefix*10+ c.to_i	
    elsif c=='.'
      pre = false
    else
      a_suffix = a_suffix*10+c.to_i
      decimals+=1
    end
  end
  return a_prefix+(a_suffix*(1.0/10.0**decimals)) 
end

return (float(a)+float(b)) # assuming a and b are input char arrays

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

#include <iostream.h>
#include <string>
using namespace std;

int main()
{
    string num1;
    string num2;
    int posdot1 = 0, posdot2 = 0; 
    int digitafterdot1 = 0, digitafterdot2 =0;
    int diff = 0;
    int num1length = 0, num2length = 0;
    char tempchar;
    
    cin>>num1;
    cin>>num2;

    posdot1 = num1.find('.');
    posdot2 = num2.find('.');

    digitafterdot1 = num1.length() - posdot1;
    digitafterdot2 = num2.length() - posdot2;

    if( digitafterdot1  > digitafterdot2 )
    {
        diff = digitafterdot1  - digitafterdot2;
        //append diff 0's to num 2
        while(diff > 0)
        {
            tempchar = 0 + '0';
            num2 = num2 + tempchar;
            diff--;
        }
        
    }
    else if( digitafterdot2  > digitafterdot1 )
    {
        diff = digitafterdot2  - digitafterdot1;
        //append diff 0's to num 2
        while(diff > 0)
        {
            tempchar = 0 + '0';
            num1 = num1 + tempchar;
            diff--;
        }
        
    }

    num1length = num1.length() - 1;
    num2length = num2.length() - 1;
    
    int carry = 0;
    string result;
    int temp = 0;
    cout<<num1<< "  "<< num2<<"\n"; 

    while((num1length >= 0) && (num2length >= 0))
    {
        if(num2[num2length] != '.') {
        temp = (num2[num2length] - '0') + (num1[num1length] - '0') + carry;
        tempchar = ((temp%10) + '0');
        result = tempchar  + result;
        carry = temp/10;
        temp = 0;        
 
        }
        else
        {
            result = '.' + result;
        }
        num1length--;
        num2length--;
    }
   
    if(num1length >= 0)
    {
        temp = 0;
        carry = 0;
        while(num1length >=0)
        {
            
            temp = (num1[num1length] - '0') + carry;
            tempchar = ((temp%10) + '0');
            result = tempchar + result;
            carry = temp/10;
            temp = 0;        
            num1length--;
        }
    }

    if(num2length >= 0)
    {
        temp = 0;
        carry = 0;
        while(num2length >=0)
        {
            temp = (num2[num2length] - '0') + carry;
            tempchar = ((temp%10) + '0');
            result = tempchar + result;
            carry = temp/10;
            temp = 0;        
            num2length--;
        }
    }

    cout<<result<<"\n";
    return 0;
}

- pc May 10, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <iostream.h>
#include <string>
using namespace std;

int main()
{
    string num1;
    string num2;
    int posdot1 = 0, posdot2 = 0; 
    int digitafterdot1 = 0, digitafterdot2 =0;
    int diff = 0;
    int num1length = 0, num2length = 0;
    char tempchar;
    
    cin>>num1;
    cin>>num2;

    posdot1 = num1.find('.');
    posdot2 = num2.find('.');

    digitafterdot1 = num1.length() - posdot1;
    digitafterdot2 = num2.length() - posdot2;

    if( digitafterdot1  > digitafterdot2 )
    {
        diff = digitafterdot1  - digitafterdot2;
        //append diff 0's to num 2
        while(diff > 0)
        {
            tempchar = 0 + '0';
            num2 = num2 + tempchar;
            diff--;
        }
        
    }
    else if( digitafterdot2  > digitafterdot1 )
    {
        diff = digitafterdot2  - digitafterdot1;
        //append diff 0's to num 2
        while(diff > 0)
        {
            tempchar = 0 + '0';
            num1 = num1 + tempchar;
            diff--;
        }
        
    }

    num1length = num1.length() - 1;
    num2length = num2.length() - 1;
    
    int carry = 0;
    string result;
    int temp = 0;
    cout<<num1<< "  "<< num2<<"\n"; 

    while((num1length >= 0) && (num2length >= 0))
    {
        if(num2[num2length] != '.') {
        temp = (num2[num2length] - '0') + (num1[num1length] - '0') + carry;
        tempchar = ((temp%10) + '0');
        result = tempchar  + result;
        carry = temp/10;
        temp = 0;        
 
        }
        else
        {
            result = '.' + result;
        }
        num1length--;
        num2length--;
    }
   
    if(num1length >= 0)
    {
        temp = 0;
        carry = 0;
        while(num1length >=0)
        {
            
            temp = (num1[num1length] - '0') + carry;
            tempchar = ((temp%10) + '0');
            result = tempchar + result;
            carry = temp/10;
            temp = 0;        
            num1length--;
        }
    }

    if(num2length >= 0)
    {
        temp = 0;
        carry = 0;
        while(num2length >=0)
        {
            temp = (num2[num2length] - '0') + carry;
            tempchar = ((temp%10) + '0');
            result = tempchar + result;
            carry = temp/10;
            temp = 0;        
            num2length--;
        }
    }

    cout<<result<<"\n";
    return 0;
}

- pc May 10, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

1) I think, after appending '0' to smaller string, both string have same size. So you need to three while loops. you can remove last two while loops.

2) you have to handle a case where string does not have '.' . this case num.find() returns -1.

- siva.sai.2020 May 12, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

correction

*you no need to write three strings*

- siva.sai.2020 May 12, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <iostream.h>
#include <string>
using namespace std;

int main()
{
    string num1;
    string num2;
    int posdot1 = 0, posdot2 = 0; 
    int digitafterdot1 = 0, digitafterdot2 =0;
    int diff = 0;
    int num1length = 0, num2length = 0;
    char tempchar;
    
    cin>>num1;
    cin>>num2;

    posdot1 = num1.find('.');
    posdot2 = num2.find('.');

    digitafterdot1 = num1.length() - posdot1;
    digitafterdot2 = num2.length() - posdot2;

    if( digitafterdot1  > digitafterdot2 )
    {
        diff = digitafterdot1  - digitafterdot2;
        //append diff 0's to num 2
        while(diff > 0)
        {
            tempchar = 0 + '0';
            num2 = num2 + tempchar;
            diff--;
        }
        
    }
    else if( digitafterdot2  > digitafterdot1 )
    {
        diff = digitafterdot2  - digitafterdot1;
        //append diff 0's to num 2
        while(diff > 0)
        {
            tempchar = 0 + '0';
            num1 = num1 + tempchar;
            diff--;
        }
        
    }

    num1length = num1.length() - 1;
    num2length = num2.length() - 1;
    
    int carry = 0;
    string result;
    int temp = 0;
    cout<<num1<< "  "<< num2<<"\n"; 

    while((num1length >= 0) && (num2length >= 0))
    {
        if(num2[num2length] != '.') {
        temp = (num2[num2length] - '0') + (num1[num1length] - '0') + carry;
        tempchar = ((temp%10) + '0');
        result = tempchar  + result;
        carry = temp/10;
        temp = 0;        
 
        }
        else
        {
            result = '.' + result;
        }
        num1length--;
        num2length--;
    }
   
    if(num1length >= 0)
    {
        temp = 0;
        carry = 0;
        while(num1length >=0)
        {
            
            temp = (num1[num1length] - '0') + carry;
            tempchar = ((temp%10) + '0');
            result = tempchar + result;
            carry = temp/10;
            temp = 0;        
            num1length--;
        }
    }

    if(num2length >= 0)
    {
        temp = 0;
        carry = 0;
        while(num2length >=0)
        {
            temp = (num2[num2length] - '0') + carry;
            tempchar = ((temp%10) + '0');
            result = tempchar + result;
            carry = temp/10;
            temp = 0;        
            num2length--;
        }
    }

    cout<<result<<"\n";
    return 0;
}

- pc May 10, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 2 vote
- Vir Pratap Uttam May 11, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Yes, there is restriction. we can not use predefined methods and parsing. We have to go with basic operations. Otherwise Amazon wouldn't have asked this question :)

- jaip42 May 11, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Is "1.2e10" legal?

- malinbupt May 11, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class ParseFloat {

  public static int indexOf(final char[] s, final char c) {
    for (int i = 0; i < s.length; i++) {
      if (s[i] == c) {
        return i;
      }
    }
    return -1;
  }

  public static int ASCII_ZERO = 48;
  public static double PRECISION = 0.0000000001;

  public static double parse(final char[] s) {

    int decimalIndex = indexOf(s, '.');
    if (decimalIndex == -1) {
      decimalIndex = s.length;
    }

    double integer = 0.0D;
    for (int i = 0; i < decimalIndex; i++) {
      final int d = s[i] - ASCII_ZERO;
      integer = (integer * 10D) + d;
    }

    double frac = 0D;
    for (int i = s.length - 1; i > decimalIndex; i--) {
      final int d = s[i] - ASCII_ZERO;
      frac = ((frac * 0.1D) + (d * 0.1D));
    }

    return integer + frac;
  }

  public static String toString(final double d) {
    int integer = (int) d;
    final int numIntDigits = (integer / 10) + 1;
    double fraction = d - integer;

    final char[] s = new char[numIntDigits];
    for (int i = numIntDigits - 1; integer != 0; i--) {
      final int digit = integer % 10;
      integer = integer / 10;
      s[i] = (char) (digit + ASCII_ZERO);
    }

    String str = new String(s);
    if (fraction != 0) {
      str = str + ".";

      while (fraction > PRECISION) {
        fraction = fraction * 10;
        final int digit = (int) fraction;
        str = str + digit;
        fraction = fraction - digit;
      }
    }
    return str;
  }

  public static void main(final String[] args) {
    final double d = parse("12.108".toCharArray());
    System.out.println(d);
    System.out.println(toString(d));

  }
}

- JayDee May 11, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

This algorithm assumes they wanted us to use the most basic functions.
First normalize both strings so they both have same number of digits before and after the decimal. This is not necessary but makes the code simpler later.
Then do simple addition on the char values, carrying any values to the next char sum.

function sumOfStrings(a, b) {

  var aIdx = a.indexOf('.');
  var bIdx = b.indexOf('.');

  if (aIdx > -1 || bIdx > -1) {
    // if one string has a decimal make sure they both do
    if (aIdx === -1) {
      a += '.';
      aIdx = a.length - 1;
    }
    if (bIdx === -1) {
      b += '.';
      bIdx = b.length - 1;
    }

    var aDecimalCount = a.length - aIdx - 1;
    var bDecimalCount = b.length - bIdx - 1;

    var maxDecimalCount = Math.max(aDecimalCount, bDecimalCount);

    // pad decimal values for one of the strings if necessary
    while (aDecimalCount < maxDecimalCount) {
      a += '0';
      aDecimalCount++;
    }
    while (bDecimalCount < maxDecimalCount) {
      b += '0';
      bDecimalCount++;
    }
  }

  // pad digits to left of decimal if necessary
  while (a.length > b.length) {
    b = '0' + b;
  }
  while (b.length > a.length) {
    a = '0' + a;
  }

  var total = '';
  var carry = 0;
  var hasDecimal = false;
  var zeroPoint = '0'.charCodeAt(0);

  for (var i = a.length - 1; i >= 0; i--) {

    var aVal = a.charCodeAt(i) - zeroPoint;
    var bVal = b.charCodeAt(i) - zeroPoint;

    // handle decimal if exists
    if (a.charAt(i) === '.') {
      if (hasDecimal) {
        throw new Error('String cannot have multiple decimal points');
      }
      hasDecimal = true;
      total = '.' + total;
      carry = 0;
      continue;
    }

    if (aVal < 0 || aVal > 9 || bVal < 0 || bVal > 9) {
      throw new Error('String values can only be numbers or decimal point');
    }

    var tmp = aVal + bVal + carry;
    carry = 0;

    if (tmp > 9) {
      carry = 1;
      tmp = tmp - 10;
    }

    total = tmp + total;
  }

  if (carry > 0) {
    total = carry + total;
  }

  return total;
}

- justinm May 17, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package com.algo;

public class StringNumberSum {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(getfromString("234.0"));
System.out.println(getfromString("9872.0"));
System.out.println(sumString("234.342","9872.0") );
}

public static float sumString(String s, String s2 ){
return getfromString(s) + getfromString(s2);
}

public static float getfromString(String s){
int i =s.indexOf(".");
float value=0.0f;
float base1=0.1f , value1=0.0f;
int base =1;
if(i!=-1){
for(int j=0; j<i; j++){
value= value+ (s.charAt(i-j-1)-'0')*base;
base=base*10;
}

for(int j=i+1; j<s.length(); j++){
value1= value1+ (s.charAt(j)-'0')*base1;
base1=base1*0.10f;
}
}
return value+value1;
}

}

- sunil singh May 18, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class Main {
	
	
	public static void main(String args[]){
		
		
		String aa = "23.45";
		String bb = "2.0002";
		System.out.println(aa);
		System.out.println(bb);
		String[] aaa = aa.split("\\.");
		String[] bbb = bb.split("\\.");
		int flag=0;
		
		int maxDigitAfterDecimal = Math.max(aaa[1].length(),bbb[1].length());
		int diff = aaa[1].length()-bbb[1].length();
		int temp = diff;
		StringBuilder zeros = new StringBuilder();
		temp = Math.abs(temp);
		while(temp>0){
			zeros.append("0");
			temp--;
		}
		if(diff>0)
			bbb[1] = bbb[1]+zeros.toString();
		else
			aaa[1] = aaa[1]+zeros.toString();
		
		StringBuilder sufix = new StringBuilder();
		temp = aaa[1].length();
		int c=0;
		while(temp>0){
			int s = Integer.parseInt(aaa[1].substring(temp-1, temp))+ Integer.parseInt(bbb[1].substring(temp-1, temp));
			s = s%10+c;
			c = s/10;
			char sc= (char)('0'+s);
			sufix.insert(0, sc);
			temp--;
		}
		String ssuffix=sufix.toString();
		int prefix = Integer.parseInt(aaa[0]) + Integer.parseInt(bbb[0]) + flag;
		String pprefix =String.valueOf(prefix);
		String result = pprefix + "." + ssuffix;
		System.out.println(result);
	}

}

- nitesh.kedia5 June 03, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

def get_float(a)
  a_prefix = 0
  a_suffix = 0
  pre = true
  decimals = 0
  a.each do |c|
    if c!='.' and pre
      a_prefix = a_prefix*10+ c.to_i	
    elsif c=='.'
      pre = false
    else
      a_suffix = a_suffix*10+c.to_i
      decimals+=1
    end
  end
  return a_prefix+(a_suffix*(1.0/10.0**decimals)) 
end

return (get_float(a))+(get_float(b))//assuming a and b are input char arrays

- Anonymous May 10, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
-2
of 2 vote

*There is no restriction provided so we can directly go for below code

private static Double stringAddition(char[] c1, char[] c2) {
		String s1=String.valueOf(c1);
		String s2=String.valueOf(c2);
		return Double.parseDouble(s1)+Double.parseDouble(s2);
	}

- Anonymous May 11, 2015 | 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