Pergunta de entrevista da empresa Google

If integer array used to store big integers (one integer store one digit), implement arithmetic operations.

Respostas da entrevista

Sigiloso

17 de jan. de 2012

# If using [1,2,3] e.g not char encoded def addBigNumbers(n1, n2): if not n1 or not n2: return n1 + n2 x = n1.pop() + n2.pop() if x >= 10: return addBigNumbers(addBigNumbers(n1, [1]), n2) + [x % 10] else: return addBigNumbers(n1, n2) + [x] # Or If using ['1', '2', '3'] style def addBigNumbersChar(n1, n2): if not n1 or not n2: return n1 + n2 x = ord(n1.pop()) + ord(n2.pop()) - 2 * ord('0') if x >= 10: return addBigNumbers(addBigNumbers(n1, [1]), n2) + [x % 10] else: return addBigNumbers(n1, n2) + [x]

1

Sigiloso

7 de abr. de 2012

Who is this guy providing bad solution when Pete gave nice solution :) People dont read what other guy wrote and how there solution compare. rediculous.

1

Sigiloso

5 de nov. de 2012

public int[] addBigInt(int[] a, int[] b){ int[] result = new int[Math.max(a.length,b.length)+1]; int aindex=a.length-1; int bindex=b.length-1; int rindex=result.length-1; int carry=0; int temp=0; while(aindex>=0 || bindex>=0 || rindex>=0){ if(bindex<0 && aindex<0){ temp=0+carry; } else if(aindex<0){ temp=b[bindex]+carry; } else if(bindex<0){ temp=a[aindex]+carry; } else{ temp=a[aindex]+b[bindex]+carry; } carry=temp/10; temp=temp%10; result[rindex]=temp; aindex--; bindex--; rindex--; } return result; }

Sigiloso

17 de jan. de 2012

The above can be simplified further for sure, just a basic solution I knocked up

Sigiloso

30 de dez. de 2011

E.g. ['1','2','3']+['2','9']=['1', '5', '2']

Sigiloso

2 de mar. de 2012

JAVA Code: package com.google.testing; public class BigIntegerOperations { /** * @param args */ public static void main(String[] args) { int[] number1 = {4,5,7,0}; int[] number2 = {5,0,7,0}; System.out.println(add(number1,number2)); } private static int add(int[] number1, int[] number2) { int num1 = getNumber(number1); int num2 = getNumber(number2); return num1+num2; } private static int getNumber(int[] arrayNumber) { int number = arrayNumber[arrayNumber.length-1]; for(int i=arrayNumber.length-2,j=1;i>=0;i--,j++) number+=(arrayNumber[i]*(getMultiple(j))); return number; } private static int getMultiple(int times) { int number = 1; for(int i=0;i

1