forked from examplehub/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSumOfTwoBigNumbers.java
More file actions
49 lines (44 loc) · 1.27 KB
/
SumOfTwoBigNumbers.java
File metadata and controls
49 lines (44 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.examplehub.maths;
import java.math.BigDecimal;
public class SumOfTwoBigNumbers {
/**
* Calculate sum of two big numbers.
*
* @param s1 the first number.
* @param s2 the second number.
* @return sum of the given two numbers.
*/
public static String sum(String s1, String s2) {
BigDecimal numberOne = new BigDecimal(s1);
BigDecimal numberTwo = new BigDecimal(s2);
BigDecimal sum = numberOne.add(numberTwo);
return sum.toString();
}
/**
* Calculate sum of two big numbers manually.
*
* @param s1 the first number.
* @param s2 the second number.
* @return sum of the given two numbers.
*/
public static String sumOf(String s1, String s2) {
char[] bytes1 = s1.toCharArray();
char[] bytes2 = s2.toCharArray();
int i1 = bytes1.length - 1;
int i2 = bytes2.length - 1;
int carry = 0;
StringBuilder builder = new StringBuilder();
while (i1 >= 0 || i2 >= 0) {
int sum = carry + (i1 != -1 ? bytes1[i1] - '0' : 0) + (i2 != -1 ? bytes2[i2] - '0' : 0);
carry = sum / 10;
builder.append(sum % 10);
if (i1 >= 0) {
i1--;
}
if (i2 >= 0) {
i2--;
}
}
return carry != 0 ? builder.append(carry).reverse().toString() : builder.reverse().toString();
}
}