Question #38504

Q) Write an interactive Java program that adds two integers of up to 50 digits each (Represents integer as an array of digits).

Expert's answer

Answer on Question#38504 - Programming, Java | JSP | JSF


package task;
import java.util.Scanner;
public class Task {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Input first integer");
        String firstInteger = input.nextLine();
        System.out.println("Input second integer");
        String secondInteger = input.nextLine();
        int[] answer = null;
        if (firstInteger.length() > secondInteger.length()) {
            answer = add(firstInteger, secondInteger);
        } else {
            answer = add(secondInteger, firstInteger);
        }
        for (int i = 0; i < answer.length; i++) {
            if (i == 0 && answer[i] == 0) {
                continue;
            }
            System.out.print(answer[i]);
        }
        System.out.println("");
    }
    public static int[] add(String firstInteger, String secondInteger) {
        int[] firstArray = new int[firstInteger.length()];
        int[] secondArray = new int[secondInteger.length()];
        int[] thirdArray = new int[firstArray.length + 1];
        int indexSecondArray = secondArray.length - 1;
        boolean needOne = false;
        int sum = 0;
        for (int i = 0; i < firstArray.length; i++) {
            firstArray[i] = ((int) firstInteger.charAt(i)) - 48;
        }
        for (int i = 0; i < secondArray.length; i++) {
            secondArray[i] = ((int) secondInteger.charAt(i)) - 48;
        }
        for (int i = firstArray.length - 1; i >= 0; i--) {
            if (indexSecondArray < 0) {
                sum = firstArray[i];
            } else {
                sum = firstArray[i] + secondArray[indexSecondArray];
            }
            if (needOne) {
                sum++;
            }
            if (sum >= 10) {
                thirdArray[i + 1] = sum % 10;
                needOne = true;
            } else {
                thirdArray[i + 1] = sum;
                needOne = false;
            }
            indexSecondArray--;
        }
        if (needOne) {
            thirdArray[0] = 1;
        }
        return thirdArray;
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

LATEST TUTORIALS
APPROVED BY CLIENTS