HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Arithmetic addition and subtraction calculator even for extremely big numbers

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
extremelynumbersadditionsubtractionbigforandevencalculatorarithmetic

Problem

Here is an attempt to sum even extremely very large numbers. As the extremely bigger numbers are fed to the method as String type this became possible. This method can accept even negative numbers also. However for positive numbers, the + sign must not be provided too.

```
import java.util.Arrays;
import java.util.Scanner;

public class SumOfLongNumbersInString {

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String firstNumber = scanner.nextLine();
String secondNumber = scanner.nextLine();
scanner.close();
System.out.println(findSumOfLongNumbersInString(firstNumber, secondNumber));
}

public static String findSumOfLongNumbersInString(String firstNumber, String secondNumber) {
boolean firstNumberNegativeFlag = false, secondNumberNegativeFlag = false;
boolean negateFlagAtEnd = false;
// Checking for positive or negative numerics only in the string
if (!firstNumber.matches("[-]?\\d++") || !secondNumber.matches("[-]?\\d++")) {
throw new IllegalArgumentException();
}
// Stripping the - symbol from the further calculation
if (firstNumber.charAt(0) == '-') {
firstNumberNegativeFlag = true;
firstNumber = firstNumber.substring(1);
}
if (secondNumber.charAt(0) == '-') {
secondNumberNegativeFlag = true;
secondNumber = secondNumber.substring(1);
}
StringBuilder result = new StringBuilder();
// Reverse both the numbers for the iteration of calculation to happen from left to right
firstNumber = new StringBuffer(firstNumber).reverse().toString();
secondNumber = new StringBuffer(secondNumber).reverse().toString();
char[] firstNumberArray = firstNumber.toCharArray();
char[] secondNumberArray = secondNumber.toCharArray();
// Making the char arrays created from the strings to be of the biggest size

Solution

First, there's the BigInteger class that facilitates this already, so if you're not reinventing-the-wheel, then you may like to consider using that class.

Other pointers:

  • Since you appear to be on Java 7 at least, please consider using try-with-resources on your Scanner instance.



  • You should stick to using StringBuilder instead of StringBuffer for your firstNumber/secondNumber declarations.



-
Your getNumeral() method can be simplified as such:

private static int getNumeral(char c) {
    if (Character.isDigit(c)) {
        return Character.digit(c, 10);
    }
    throw new IllegalArgumentException();
}

Code Snippets

private static int getNumeral(char c) {
    if (Character.isDigit(c)) {
        return Character.digit(c, 10);
    }
    throw new IllegalArgumentException();
}

Context

StackExchange Code Review Q#100535, answer score: 4

Revisions (0)

No revisions yet.