Algorithm: How to add two large numbers

question

Realize the addition of two very large numbers and find their sum.

Require

1. It is an integer;
2. The two numbers are infinite and cannot fit in a long;
3. BigInteger cannot be used;
4. The calculation method provided by any wrapper class cannot be used;
5. Both numbers are provided in the form of strings.

The following algorithm is optimized and organized according to the book "Comic Algorithm" Xiao Hui's Algorithmic Journey, combined with his own experience.

train of thought

  1. Use arrays to handle large numbers
  2. Use "vertical" traversal and addition, and the result is stored in an array.
  3. Finally, it can be realized by reversing the array to String.

Code

package practise;
/**
 * <pre>
 *     author : June Yang
 *     time   : 2022/07/25
 *     desc   : 两个大数相加
 *     version: 1.0
 * </pre>
 */
public class BigNumAdd {
    
    
    public static void main(String[] args) {
    
    
        System.out.println(bigNumberNum("6868", "128080989089093"));
    }
    public static String bigNumberNum(String bigNumberA, String bigNumBerB) {
    
    
        int maxLength = Math.max(bigNumberA.length(), bigNumBerB.length());
        int[] arrayA = new int[maxLength + 1];
        // 将 String 转化成 int
        for (int i = 0; i < bigNumberA.length(); i++) {
    
    
            arrayA[i] = bigNumberA.charAt(bigNumberA.length() - 1 - i) - '0';
        }
        int[] arrayB = new int[maxLength + 1];
        // 将 String 转化成 int
        for (int i = 0; i < bigNumBerB.length(); i++) {
    
    
            arrayB[i] = bigNumBerB.charAt(bigNumBerB.length() - 1 - i) - '0';
        }
        // 得到结果的数组
        int[] result = new int[maxLength + 1];

        // 核心算法:竖式相加 满 10 进 1
        for (int i = 0; i < result.length; i++) {
    
    
            int temp = result[i];
            temp += arrayA[i];
            temp += arrayB[i];

            if (temp >= 10) {
    
    
                temp = temp - 10;
                result[i + 1] = 1; // 将进位后的 1 存到数组的下一位
            }
            result[i] = temp;
        }
        // 将 result 数组倒序之后再转成 String
        StringBuilder sb = new StringBuilder();
        boolean findFist = false;
        for (int i = result.length - 1; i >= 0; i--) {
    
    
            if (!findFist) {
    
    
                if (result[i] == 0) {
    
    
                   continue;  // continue 的作用:跳过当前循环继续下一个循环。此处 用于跳过结果数组末尾的 "0"
                }
                findFist = true;
            }
            sb.append(result[i]);
        }
        return sb.toString();
    }
}

summary:

The time complexity is o(n). Algorithms can be further optimized.
There are many solutions to the addition of large numbers on the Internet. Personally, I think this solution is easier to understand and easy to use.
After understanding the above key points, it is easy to write.

Further reading:

  1. Learn more about the utility classes BigInterger and BigDecimal in java.
  2. Other related algorithms:
    LeetCode string multiplication
    LeetCode character addition

Guess you like

Origin blog.csdn.net/jun5753/article/details/125980421