# Summing 2 Integers Together (not as easy as it sounds)

• 11-03-2011, 08:40 AM
Zora
Summing 2 Integers Together (not as easy as it sounds)
Alright, here's the question.

Quote:

Write a java program to read two integer numbers each up to 30 digits, and then add them and print the result along with input numbers.. Example: Assume the first number is 39983928349458 and the second number is equal to 92387486729, then the output should be as follow.

Output:

39,983,928,349,458+
92,387,486,729
--------------------
40,076,315,836,187

Note1: You should input your numbers without comma, but the output should be printed with comma as shown in the example.
Note2: You are not allowed to use java's BigInteger, BigDecimal, or similar classes. You should use arrays and create your own algorithm, otherwise, you will not be marked.
Seems rather difficult, but I'm currently trying to figure out how to separate each set of 3 numbers. I don't know what I'm supposed to do for 1 and 2 digits. When summing up the 2 inputs together, I actually have to work with each individual digit right? And in that case, I'll have to create an array and initialize the size according to the length of the input.

Sorry if this sounds like complete BS, I'm not very good with these programming terminologies. Could I get some guidance?
• 11-03-2011, 09:05 AM
Eranga
Re: Summing 2 Integers Together (not as easy as it sounds)
Step down. Arithmetic calculation and the output representation done separately. Then it will make your life easy. :)

Did you tried anything yet?
• 11-03-2011, 09:14 AM
Eranga
Re: Summing 2 Integers Together (not as easy as it sounds)
The following simple code segment do the calculation part,

Code:

```import java.util.Scanner; import java.math.BigInteger; class AddNumbers {                 static Scanner console = new Scanner(System.in);                 public static void main(String[] args) {                 System.out.println("1st number; ");                 BigInteger bigInteger1 = new BigInteger(console.next());                                 System.out.println("2nd number; ");                 BigInteger bigInteger2 = new BigInteger(console.next());                                 BigInteger bigSum = bigInteger1.add(bigInteger2);                 System.out.println(bigSum);         } }```
• 11-03-2011, 09:32 AM
Eranga
Re: Summing 2 Integers Together (not as easy as it sounds)
How funny it is. With the basis stuff I did this in couple of min.

Code:

```import java.util.Scanner; import java.math.BigInteger; import java.text.*; class AddNumbers {                 static Scanner console = new Scanner(System.in);                 public static void main(String[] args) {                 System.out.print("1st number; ");                 BigInteger bigInteger1 = new BigInteger(console.next());                                 System.out.print("2nd number; ");                 BigInteger bigInteger2 = new BigInteger(console.next());                                 BigInteger bigSum = bigInteger1.add(bigInteger2);                 DecimalFormat myFormatter = new DecimalFormat("###,###");                 String output1 = myFormatter.format(bigInteger1);                 String output2 = myFormatter.format(bigInteger2);                 String output3 = myFormatter.format(bigSum);                                 int len1 = output1.length();                 int len2 = output2.length();                 int max = (len1 > len2) ? len1 : len2;                 int diff = (len1 > len2) ? (len1 - len2) : (len2 - len1);                                 String dum = "";                 for(int spaces = 0; spaces < diff; spaces++) {                         dum += " ";                 }                                 if(len1 < len2) {                         output1 = dum + output1;                 }                 else {                         output2 = dum + output2;                 }                                 System.out.println("\n" + output1);                 System.out.println(output2 + " +");                                 for(int index = 0; index < max; index++) {                         System.out.print("-");                 }                                 System.out.println("\n" + output3);         } }```
• 11-03-2011, 09:46 AM
JosAH
Re: Summing 2 Integers Together (not as easy as it sounds)
Quote:

Originally Posted by Eranga
The following simple code segment do the calculation part,

Read note #2 in the assignment text: you're not allowed to use BigIntegers; you're supposed to do it all by yourself ;-)

kind regards,

Jos
• 11-03-2011, 09:56 AM
Eranga
Re: Summing 2 Integers Together (not as easy as it sounds)
Oh I miss it. :S

Still it is possible. By recursive with the integers.
• 11-03-2011, 12:35 PM
Eranga
Re: Summing 2 Integers Together (not as easy as it sounds)
Bit late, just finish my lunch ;)

Have a look at the following code segment.

Code:

```import java.util.Scanner; class AddNumbers {                 static Scanner console = new Scanner(System.in);                 public static void main(String[] args) {                 // Get the first number from the user                 System.out.print("1st number; ");                 String strInput1 = console.next();                                 // Get the second number from the user                 System.out.print("2nd number; ");                 String strInput2 = console.next();                                 // Identified which one is the lenghty one, not the larger one                 String max_len = (strInput1.length() > strInput2.length()) ? strInput1 : strInput2;                 String min_len = (strInput1.length() > strInput2.length()) ? strInput2 : strInput1;                                 // Split into digits and store them in an array                 String[] digits1 = max_len.split("(?<=.)");                 String[] digits2 = min_len.split("(?<=.)");                                 // Dummy array to format the smallest array above                 String[] digits3 = new String[digits1.length];                                 // If the numbers are not in the same size adjust the index on the smallest                 if(digits1.length > digits2.length) {                         digits3 = new String[digits1.length];                         for(int i = 0; i < digits3.length; i++) {                                 digits3[i] = "0";                         }                         int iCount = digits3.length;                         for(int j = (digits2.length - 1); j >= 0 ; j--) {                                 digits3[--iCount] = digits2[j];                         }                 }                 int val = 0;                 int mod = 0;                 int up = 0;                 int low = 0;                                 String sum = "";                                 // Addition of two numbers                 for(int index = (digits1.length - 1); index >= 0; index--) {                         up = Integer.parseInt(digits1[index]);                                                 if(digits1.length > digits2.length)                                 low = Integer.parseInt(digits3[index]);                         else                                 low = Integer.parseInt(digits2[index]);                                                 mod = (up + low + val) % 10;                         val = (up + low + val) / 10;                                                 sum = mod + sum;                 }                                 // Display the result. Test with any large number :)                 sum = ((val == 0) ? "" : val) + "" + sum;                 System.out.println(sum);         } }```
You have to do the formatting and display accordingly. Since you cannot use BigInteger and all you have to implement yourself the formatting. Simple regex manipulation works fine. Play around and let me know.

There are many ways to do the same, and I tried my best to keep the solution simple as possible. If you are not clear with anything please let me know. Good luck! :)
• 11-03-2011, 12:42 PM
Grkn
Re: Summing 2 Integers Together (not as easy as it sounds)
It can write your code with 2 int array

Integer []firstNumber=new Integer[30];
Integer []secondNumber=new Integer[30];

you can use byte array for performance issues.

So as you can see array has 30 digits and each cell (C) ' value must be 0<= C <=9.

You have to use one more thing.
Just fill the array with -1 values;

Ex:
12345
1,2,3,4,5
4-3-2-1-0 //Index of Array that corresponds to value

//JUST calculating value . You have to design a little different way

int value=0;
for(int indexOfArrayCell=0;indexOfArrayCell<array.length;i ndexOfArrayCell++){
if(indexOfArrayCell !=-1)
value=value+array[indexOfArrayCell]+pow(10,indexOfArrayCell);
}

This is just a small example. You can't use (int value) to get sum. You have to keep those values in array.
• 11-03-2011, 12:49 PM
Eranga
Re: Summing 2 Integers Together (not as easy as it sounds)
Quote:

Originally Posted by Grkn
You can't use (int value) to get sum. You have to keep those values in array.

What you mean by this?
• 11-03-2011, 01:29 PM
Grkn
Re: Summing 2 Integers Together (not as easy as it sounds)
int value can not contain 30 digit number so you can not put value into int
• 11-03-2011, 11:26 PM
Zora
Re: Summing 2 Integers Together (not as easy as it sounds)
Whoa I didn't expect to see the full written code! It's amazing how things like BigInteger, BigSum, etc...can save a lot of time. Though, I shouldn't use this unless I understand how it works, so I need some clarification.

Could you explain these segments in a bit more detail:

Code:

```String max_len = (strInput1.length() > strInput2.length()) ? strInput1 : strInput2; String min_len = (strInput1.length() > strInput2.length()) ? strInput2 : strInput1; if(digits1.length > digits2.length) {             digits3 = new String[digits1.length];             for(int i = 0; i < digits3.length; i++) {                 digits3[i] = "0";             }             int iCount = digits3.length;             for(int j = (digits2.length - 1); j >= 0 ; j--) {                 digits3[--iCount] = digits2[j];             }         } if(digits1.length > digits2.length)                 low = Integer.parseInt(digits3[index]);             else                 low = Integer.parseInt(digits2[index]);```
I've never used parseInt before. I'm also in the middle of modifying your code into methods and arrays, since that's what I'm supposed to use.
• 11-07-2011, 01:36 AM
rajkapur
Re: Summing 2 Integers Together (not as easy as it sounds)
Why prefer console in place scanner;
• 11-07-2011, 01:52 AM
pbrockway2
Re: Summing 2 Integers Together (not as easy as it sounds)
Quote:

Originally Posted by rajkapur
Why prefer console in place scanner;

Do you mean in Eranga's code?

He *was* using Scanner rather than Console. He used the variable console as this is a common way of referring to a something (input stream, reader, scanner, etc) that depends ultimately on System.in.
• 11-07-2011, 06:24 AM
Eranga
Re: Summing 2 Integers Together (not as easy as it sounds)
First of all, sorry for the late reply.

Quote:

Originally Posted by Zora
Whoa I didn't expect to see the full written code! It's amazing how things like BigInteger, BigSum, etc...can save a lot of time. Though, I shouldn't use this unless I understand how it works, so I need some clarification.

Normally I didn't do this, just pasting the full code relevant to OPs' question. Actually I really hate it. :o: However, your question title gives an impression to give a try.

Quote:

Originally Posted by Zora
Could you explain these segments in a bit more detail:

Of course.

Code:

```String max_len = (strInput1.length() > strInput2.length()) ? strInput1 : strInput2; String min_len = (strInput1.length() > strInput2.length()) ? strInput2 : strInput1;```
As you seen, I have stored digits of two user entered numbers in two separate arrays. So I can process digits, rather dealing with the whole number, which is quite difficult. Then in the above code segment I identified which number (actually the array with digits) is the longest (not the largest). Reason is, which ever the order that user entered the two numbers, I want to use the same logic.

Code:

```if(digits1.length > digits2.length) {             digits3 = new String[digits1.length];             for(int i = 0; i < digits3.length; i++) {                 digits3[i] = "0";             }             int iCount = digits3.length;             for(int j = (digits2.length - 1); j >= 0 ; j--) {                 digits3[--iCount] = digits2[j];             }         }```

Once I found the longest and shortest numbers, arrange them as follows

Quote:

XXXXXXXX --> Longest number
XXXXX --> Shortest number
So you can see on left-most digits there is a mismatch, and it is not possible to simple add the corresponding digits from both numbers after a certain. So fill with zeros.

Quote:

XXXXXXXX --> Longest number
000XXXXX --> Shortest number
Then you can simple add relevant starting from right-most digit. Still you are not clear with something let me know.
• 11-07-2011, 06:25 AM
Eranga
Re: Summing 2 Integers Together (not as easy as it sounds)
Quote:

Originally Posted by rajkapur
Why prefer console in place scanner;

You got the best explanation from pbrockway2s' post.