码迷,mamicode.com
首页 > 其他好文 > 详细

大数相加

时间:2014-12-31 01:03:21      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:

大数相加

public class VeryBigNumAdd {   
  
    public static void main(String[] args) {   
        VeryBigNumAdd vbn = new VeryBigNumAdd();   
        String a = "123453243455535634535252345234677576252241234123523453664563634";   
        String b = "123453243455535634535252345234677576252241234123523453664563634";   
        String result = vbn.doAdd(a, b);   
        System.out.println("result:" + result);   
    }   
  
    String doAdd(String a, String b) {   
        String str = "";   
        int lenA = a.length();   
        int lenB = b.length();   
        int maxLen = (lenA > lenB) ? lenA : lenB;   
        int minLen = (lenA < lenB) ? lenA : lenB;   
        String strTmp = "";   
        for (int i = maxLen - minLen; i > 0; i--) {   
            strTmp += "0";   
        }   
        // 把长度调整到相同   
        if (maxLen == lenA) {   
            b = strTmp + b;   
        } else  
            a = strTmp + a;   
        int JW = 0;// 进位   
        for (int i = maxLen - 1; i >= 0; i--) {   
            int tempA = Integer.parseInt(String.valueOf(a.charAt(i)));   
            int tempB = Integer.parseInt(String.valueOf(b.charAt(i)));   
            
            int temp;   
            if (tempA + tempB + JW >= 10 && i != 0) {   
                temp = tempA + tempB + JW - 10;   
                JW = 1;   
            } else {   
                temp = tempA + tempB + JW;   
                JW = 0;   
            }   
            str = String.valueOf(temp) + str;   
        }   
        return str;   
    }   
}   
运行程序:
C:\bat>java  VeryBigNumAdd
result:246906486911071269070504690469355152504482468247046907329127268

 

大数相加

标签:

原文地址:http://www.cnblogs.com/aicpcode/p/4194836.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!