java实现两个大数相加,可能存在溢出。

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


public class BigIntegerAddition {

	/**
	 * 题目:java实现两个大数相加,可能存在溢出。
	 * 如123456789 + 987654321 返回 1111111110
	 * 1.直接用BigInteger
	 * 2.模拟手算加法,进位相加(暂时没有考虑负数的情况)
	 */
	public static void main(String[] args) {

		String x="23456789";
		String y="987654321";
		//use BigInter
		BigInteger a=new BigInteger(x);
		BigInteger b=new BigInteger(y);
		BigInteger c=a.add(b);
		System.out.println(c.toString());
		//"reinvent the wheel"
		String d=add(x,y);
		System.out.println(d);
		
	}

	//return x+y. Have not considered the negative number yet.
	public static String add(String x,String y){
		if(x==null||y==null){
			return null;
		}
		if(!isNumeric(x)||!isNumeric(y)){
			return null;
		}
		if(x.equals("0")){
			return y;
		}
		if(y.equals("0")){
			return x;
		}
		
		if(x.length()>y.length()){
			String tmp=x;
			x=y;
			y=tmp;
		}
		
		x=addZeroToFirst(x,y.length());
		String z=addHelp(x,y);
		return z;
	}
	
	public static String addHelp(String x,String y){
		String z="";
		int len=x.length();
		int[] a=toIntArray(x);
		int[] b=toIntArray(y);
		int[] c=new int[len+1];
		int d=0;//to carry. No need to use int[]
		for(int i=0;i<len;i++){
			int tmpSum=a[len-1-i]+b[len-1-i]+d;
			c[len-i]=tmpSum%10;
			d=tmpSum/10;
		}
		c[0]=d;
		StringBuilder sb=new StringBuilder();
		for(int i=0;i<=len;i++){
			sb.append(c[i]);
		}
		if(c[0]==0){//delete the first '0' in result string
			z=sb.substring(1);
		}else{
			z=sb.toString();
		}
		return z;
	}
	

	//String - toCharArray - toIntArray
	public static int[] toIntArray(String str){
		int len=str.length();
		int[] result=new int[len];
		for(int i=0;i<len;i++){
			result[i]=str.charAt(i)-'0';
		}
		return result;
	}
	
	//("123",5)-->"00123"
	public static String addZeroToFirst(String str,int length){
		StringBuilder sb=new StringBuilder();
		int diff=length-str.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 isNum=p.matcher(str);
		return isNum.matches();
	}
}

你可能感兴趣的:(java实现)