Java implements the addition of large numbers-arithmetic addition method

Java implements the addition of large numbers-arithmetic addition method

principle

Input two numeric strings, add them bit by bit according to the arithmetic addition rules, carry, and return an added string.

step

  1. The two strings are converted to int arrays;
  2. Align the length of the two arrays, fill the high bits with 0;
  3. Add bit by bit
  4. The final result, if the 0th element is 0, remove it.

Code

Additive logic

public static String sum(String firstNum, String secondNum) {

        if (null == firstNum || null == secondNum) {
            return "";
        }

        int length = firstNum.length() >= secondNum.length() ? firstNum.length() : secondNum.length();

        // int , 0.
        int[] firstArr = paddingArray(toIntArray(firstNum.toCharArray()), length);
        int[] secondArr = paddingArray(toIntArray(secondNum.toCharArray()), length);

        int[] result = new int[length + 1];

        // 
        boolean carried = false;

        // 
        for (int pos = length - 1; pos >= 0; pos--) {

            int sum = firstArr[pos] + secondArr[pos];
            if (carried) {
                sum++;
            }
            
            carried = false;
            if (sum > 9) {
                sum = sum % 10;
                carried = true;
            }

            result[pos + 1] = sum;
        }
        
        if (carried) {
            result[0] = 1;
        }

        StringBuilder builder = new StringBuilder();
        for (int i : result) {
            builder.append(i);
        }

        // 0 0, 1 .
        if (builder.charAt(0) == '0') {
            return builder.substring(1);
        }
        return builder.toString();

    }

 

String to int array

private static int[] toIntArray(char[] src) {
        int[] result = new int[src.length];
        for (int i = 0; i < src.length; i++) {
            char c = src[i];
            if (c < 48 || c > 57) {
                //ascii , 48->57   0->9
                throw new NumberFormatException(c + " not a number");
            }
            int num = c - 48;
            if (num < 0) {
                num = 0;
            }
            result[i] = num;
        }
        return result;
    }
 

Array length alignment

    /*
     , 0 .
    */
    private static int[] paddingArray(int[] arr, int length) {
        if (arr.length == length) {
            return arr;
        }

        int[] result = new int[length];
        int pos = length - arr.length;

        System.arraycopy(arr, 0, result, pos, arr.length);

        return result;
    }