两个超长数字字符串相加,未实现相减和带小数点的

2020-11-27  本文已影响0人  王冥

需求两个很长的字符串数字相加,不使用第三方函数,手写算法,目前只写了不带小数点的相加,减法也没实现

public class AddLongStr {
    
    private static String addNumStr(String str1,String str2) {
        StringBuilder sumNum = new StringBuilder();
        int len = str1.length();
        int len1 = str1.length();
        int len2 = str2.length();
        String gaoW = "";
        if (len1 > len2) {
            len = str2.length();
            gaoW = str1.substring(0, len1 - len);
        }else {
            len = str1.length();
            gaoW = str2.substring(0, len2 - len);
        }
        System.out.println("len="+len);
        int ten = 0;
        for (int i = 1; i<=len; i++) {
            int sum = Integer.parseInt(String.valueOf(str1.charAt(len1-i))) + Integer.parseInt(String.valueOf(str2.charAt(len2-i))) + ten;
            ten = sum/10;
            sumNum.insert(0, sum%10);
        }
        System.out.println("sumNum="+sumNum.toString());
        StringBuilder gaoSumString =new StringBuilder();
        if (null != gaoW && !gaoW.equals("")) {
            System.out.println("gaoW="+gaoW);
            int sl = gaoW.length();
            int ten2 = 0;
            for (int i = sl-1; i >=0; i--) {
                int sum = 0;
                if (i==sl-1) {
                    sum = (Integer.parseInt(String.valueOf(gaoW.charAt(i)))) + ten+ ten2;
                }else {
                    sum = (Integer.parseInt(String.valueOf(gaoW.charAt(i)))) + ten2;
                }
                ten2 = sum/10;
                gaoSumString.insert(0, sum%10);
            }
            if (ten2>0) {
                gaoSumString.insert(0, ten2);
            }
            
        }
        sumNum = gaoSumString.append(sumNum);
        return sumNum.toString();
    }
    
    public static void main(String[] args) {
        
        System.out.println(addNumStr("777","99933"));
    }

}

有兴趣的可以一起检查错误和优化完善,相减和带小数点的

上一篇下一篇

猜你喜欢

热点阅读