加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

大数相加

发布时间:2020-12-14 01:32:30 所属栏目:大数据 来源:网络整理
导读:/** * Created by syh on 2016/9/20. * 大数相加 */public class BigNumber { public static void main(String[] args) { String num1 = "1045"; String num2 = "55"; System.out.println(add(num1,num2)); } /** * 用字符串模拟两个大数相加 */ public stat
/**
 * Created by syh on 2016/9/20.
 * 大数相加
 */
public class BigNumber {
    public static void main(String[] args) {
        String num1 = "1045";
        String num2 = "55";
        System.out.println(add(num1,num2));
    }

    /**
     * 用字符串模拟两个大数相加
     */
    public static String add(String n1,String n2) {
        StringBuilder result = new StringBuilder();

        // 1 反转字符串
        String number1 = new StringBuffer(n1).reverse().toString();
        String number2 = new StringBuffer(n2).reverse().toString();

        // 2 把两个字符串补齐,即短字符串的高位用0补齐
        int len1 = number1.length();
        int len2 = number2.length();
        int maxLen = len1 > len2 ? len1 : len2;
        if (len1 < len2) {
            for (int i = len1; i < len2; i++) {
                number1 += "0";
            }
        } else if (len1 > len2) {
            for (int i = len2; i < len1; i++) {
                number2 += "0";
            }
        }

        // 3 把两个正整数相加,一位一位的加并加上进位
        boolean overFlow = false; //是否进位
        for (int i = 0; i < maxLen; i++) {
            int sum = Integer.parseInt(number1.charAt(i) + "") + Integer.parseInt(number2.charAt(i) + "");
            if (overFlow) {
                sum += 1;
            }

            if (sum >= 10) {
                overFlow = true;
                result.append(sum - 10);
            } else {
                overFlow = false;
                result.append(sum);
            }
        }

        // 4 最高位
        if (overFlow) {
            result.append("1");
        }
        return result.reverse().toString();
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读