Algorithm Question: Add Two Large Numbers (java)

Topic:
The basic int type cannot be directly used for the addition of large numbers, because the integers that int can represent are limited and cannot meet the requirements of large numbers. Two large numbers entered may be positive or negative

Analysis:
First, you need to judge the positive and negative signs of two large numbers, and use strings to simulate the addition and subtraction of two numbers in elementary school mathematics.

Code:

/**
 * 两个大数相加,输入的两个大数的正负号不确定
 */
public class Solution {

    public static void main(String[] args) {
        String str1 = "8541269855";
        String str2 = "-6985326589745555";

        //返回的结果
        String res = null;

        //如果两个大数都是负数
        if(str1.charAt(0) == '-' && str2.charAt(0) == '-'){
            str1 = str1.substring(1);
            str2 = str2.substring(1);
            res = bigNumberAdd(str1, str2);
            res = "-" + res;
        }
        //如果两个大数中,一个负数,一个正数
        else if(str1.charAt(0) == '-' || str2.charAt(0) == '-'){
            if(str1.charAt(0) == '-'){
                str1 = str1.substring(1);
                if(compare(str1, str2) == 1){
                    res = "-" + bigNumberSub(str1, str2);
                }
                else if(compare(str1, str2) == -1){
                    res = bigNumberSub(str2, str1);
                }
                else{
                    res = "0";
                }
            }
            else{
                str2 = str2.substring(1);
                if(compare(str1, str2) == 1){
                    res = bigNumberSub(str1, str2);
                }
                else if(compare(str1, str2) == -1){
                    res = "-" + bigNumberSub(str2, str1);
                }
                else{
                    res = "0";
                }
            }
        }
        //两个大数都是正数
        else{
            res = bigNumberAdd(str1, str2);
        }
        System.out.println(res);
    }

    /**
     * 两个大数相减
     * 假设str1-str2,并且str1大于str2
     */
    public static String bigNumberSub(String str1, String str2) {
        char[] arr1 = new StringBuilder(str1).reverse().toString()
                .toCharArray();
        char[] arr2 = new StringBuilder(str2).reverse().toString()
                .toCharArray();

        int len1 = arr1.length;
        int len2 = arr2.length;
        int len = len1 > len2 ? len1 : len2;
        int[] arr = new int[len];
        for (int i = 0; i < len; i++) {
            int ch1 = i < len1 ? (arr1[i]-'0') : 0;
            int ch2 = i < len2 ? (arr2[i]-'0') : 0;
            arr[i] = ch1 - ch2;
        }

        for (int i = 0; i < len; i++) {
            if (arr[i] < 0) {
                arr[i + 1] -= 1;
                arr[i] += 10;
            }
        }

        StringBuilder result = new StringBuilder();
        boolean flag = false;
        for (int i = len - 1; i >= 0; i--) {
            if (arr[i] == 0 && flag == false) {
                continue;
            } else {
                flag = true;
            }
            result.append(arr[i]);
        }
        return result.toString();
    }

    /**
     * 两个大数都是正数,相加
     */
    public static String bigNumberAdd(String str1, String str2) {
        int len1 = str1.length();
        int len2 = str2.length();
        char[] arr1 = new StringBuilder(str1).reverse().toString()
                .toCharArray();
        char[] arr2 = new StringBuilder(str2).reverse().toString()
                .toCharArray();

        int len = len1 > len2 ? len1 : len2;
        int[] arr = new int[len + 1];
        for (int i = 0; i < len + 1; i++) {
            int num1 = i < len1 ? (arr1[i]-'0') : 0;
            int num2 = i < len2 ? (arr2[i]-'0') : 0;
            arr[i] = num1 + num2;
        }

        for (int i = 0; i < len + 1; i++) {
            if(arr[i] > 10){
                arr[i+1] += arr[i] / 10;
                arr[i] = arr[i] % 10;
            }
        }

        StringBuilder result = new StringBuilder();
        boolean flag = true;
        for(int i=len;i>=0;i--){
            if(arr[i] == 0 && flag){
                continue;
            }else{
                flag = false;
            }
            result.append(arr[i]);
        }
        return result.toString();
    }

    /**
     * 比较两个大数,是否第一个大数大于第二个大数
     * @return 1表示str1大于str2; -1表示str1小于str2; 0表示str1与str2相等 
     */
    public static int compare(String str1, String str2) {
        int len1 = str1.length();
        int len2 = str2.length();
        if (len1 > len2) {
            return 1;
        } else if (len1 < len2) {
            return -1;
        }

        int index = 0;
        while (true) {
            if (str1.charAt(index) > str2.charAt(index)) {
                return 1;
            } else if (str1.charAt(index) < str2.charAt(index)) {
                return -1;
            } else {
                if (index == len1 - 1) {
                    return 0;
                }
                index++;
            }
        }
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325609057&siteId=291194637