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

1. Member Join Date
Sep 2011
Posts
21
Rep Power
0

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

Alright, here's the question.

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?  Reply With Quote

2. ## 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?  Reply With Quote

3. ## Re: Summing 2 Integers Together (not as easy as it sounds)

The following simple code segment do the calculation part,

Java Code:
```import java.util.Scanner;
import java.math.BigInteger;

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());

System.out.println(bigSum);
}
}```  Reply With Quote

4. ## 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.

Java Code:
```import java.util.Scanner;
import java.math.BigInteger;
import java.text.*;

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());

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);
}
}```  Reply With Quote

5. ## Re: Summing 2 Integers Together (not as easy as it sounds) 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  Reply With Quote

6. ## 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.  Reply With Quote

7. ## 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.

Java Code:
```import java.util.Scanner;

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 = "";

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! :)  Reply With Quote

8. Member Join Date
Oct 2011
Posts
65
Rep Power
0

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

It can write your code with 2 int array

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

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.  Reply With Quote

9. ## Re: Summing 2 Integers Together (not as easy as it sounds) 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?  Reply With Quote

10. Member Join Date
Oct 2011
Posts
65
Rep Power
0

## 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  Reply With Quote

11. Member Join Date
Sep 2011
Posts
21
Rep Power
0

## 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:

Java 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.  Reply With Quote

12. Member Join Date
Nov 2011
Location
india
Posts
1
Rep Power
0

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

Why prefer console in place scanner;  Reply With Quote

13. Moderator   Join Date
Feb 2009
Location
New Zealand
Posts
4,716
Rep Power
17

## Re: Summing 2 Integers Together (not as easy as it sounds) 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.  Reply With Quote

14. ## Re: Summing 2 Integers Together (not as easy as it sounds)

First of all, sorry for the late reply. 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. However, your question title gives an impression to give a try. Originally Posted by Zora Could you explain these segments in a bit more detail:
Of course.

Java 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.

Java 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

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.

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.  Reply With Quote

15. ## Re: Summing 2 Integers Together (not as easy as it sounds) Originally Posted by rajkapur Why prefer console in place scanner;
You got the best explanation from pbrockway2s' post.  Reply With Quote

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•