大整数加法

java实现

package 经典;

import java.math.BigInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class BigIntegerAddition {
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        
        String x="12314123112313";
        String y="10889129018390813908";
        String z;
        
        BigInteger a=new BigInteger(x);
        BigInteger b=new BigInteger(y);
        z=a.add(b).toString();
        
        System.out.println(z);
        
        System.out.println(add(x,y));
    }
    
    
    public static int[] toIntArray(String str){
        int length=str.length();
        int[] a=new int[length];
        
        for(int i=0; i<length; i++)
            a[i]=str.charAt(i)-'0';
    
        return a;    
    }
    
    
    public static String add(String a,String b){
        if(a==null||b==null)
            return null;
        if(!isNumeric(a)||!isNumeric(b))
            return null;
        if(a.equals("0"))
            return b;
        if(b.equals("0"))
            return a;
        if(a.length()==b.length())
        {
            return addHelp(a,b);
        }
        else if(a.length()>b.length())
        {
            String x=a;
            String y=addZeroToFirst(b, a.length());
            return addHelp(x,y);
        }
        else
        {
            String y=b;
            String x=addZeroToFirst(a, b.length());
            return addHelp(x,y);
        }
        
    }
    
    public static String addHelp(String a,String b){
        
        int length=a.length();
        int[] x=toIntArray(a);
        int[] y=toIntArray(b);    
        int[] z=new int[length+1];
        int temp;
        int diff=0;
        
        for(int i=length; i>0; i--)
        {
            temp=x[i-1]+y[i-1]+diff;
            z[i]=temp%10;
            diff=temp/10;
        }
        z[0]=diff;
        
        StringBuilder sb=new StringBuilder();
        for(int i=1-diff; i<=length; i++)
        {
            sb.append(z[i]);
        }
        
        return sb.toString();
    }
    
    public static String addZeroToFirst(String str,int n){
        
        StringBuilder sb=new StringBuilder();
        int length=str.length();
        int diff=n-length;
        while(diff>0)
        {
            sb.append("0");
            diff--;
        }
        
        sb.append(str);
        
        return sb.toString();
        
    }
        
    public static boolean isNumeric(String str){
        Pattern p=Pattern.compile("[0-9]*");
        Matcher m=p.matcher(str);
        return m.matches();
    }
}

 

posted @ 2014-10-05 09:23  凡尘里的一根葱  阅读(466)  评论(0编辑  收藏  举报