0

Today I had an interview and the interviewer asked to make a program for addition of two numbers, I get shocked how can he give a simple question but the question is different

the length of two number can be anything (10,20,30 or even 1000 etc.)

  • if you convert it to int,double,long double if the number is greater than their range than the answer can be wrong.

Please help me for the question.

Saurabh Shrivastava
  • 1,055
  • 1
  • 12
  • 26
JeeVan TiWari
  • 325
  • 2
  • 15
  • Than please provide the link. – JeeVan TiWari Jun 14 '17 at 16:49
  • you can find heaps of duplicates in the tag [tag:bigint] – phuclv Jun 14 '17 at 16:52
  • Infinite length numbers? According to [Knuth](https://en.wikipedia.org/wiki/Algorithm_characterizations#1968.2C_1973_Knuth.27s_characterization) "An algorithm must always terminate after a finite number of steps," so there can be no such algorithm. What kind of a silly person would ask you to write a program for which there is no valid algorithm? Are you sure they didn't ask for how to add numbers of arbitrary but finite length? – pjs Jun 14 '17 at 17:03
  • Its interview question I can't say simply a+b = answer – JeeVan TiWari Jun 14 '17 at 17:05

1 Answers1

1

You can always take the two numbers in arrays (i.e. arrays have digits of the numbers as elements) and add them as we add manually i.e. start from one's digit and store the carry if it's present then do the same for ten's digit, then hundred's digit and so on.

Say you want to add 123 and 329.

X = 123, X[] = [1,2,3]
Y = 329, Y[] = [3,2,9]

You start with one's digit (the rightmost or last element) and add the elements of both X and Y arrays and add carry to it (initially set to 0). If the addition comes out to be greater than 10, set carry = sum / 10 (since we are adding each element, this carry shall always be either 0 or 1) and the addition to add [i] = sum % 10. Repeat till all the elements of smaller array are over. Then add the carry to remaining elements of larger array continuing the above logic.

carry = 0
Step 1 : 3 + 9 + carry (0) = 5, carry => 12 / 10 = 1, add => 12 % 10 = 2
Step 2 : 2 + 2 + carry (2) = 6, carry => 6 / 10 = 0, add => 6 % 10 = 6
Step 3 : 3 + 1 + carry (0) = 4, carry => 4 / 10 = 0, add => 4 % 10 = 4

Ans = 462

Obviously the array storing sum may have one digit extra so take care of that as well.

Saurabh Shrivastava
  • 1,055
  • 1
  • 12
  • 26