`

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();
	}
}

0
1
分享到:
评论
6 楼 neyshule 2012-06-14  
sorry, miss type it, should be another question.
5 楼 neyshule 2012-06-14  
第一种解法扩号不对称啊,是内部类吗?
4 楼 bylijinnan 2012-04-13  
dolphin_lzy 写道
很好啊,支持你!

3 楼 dolphin_lzy 2012-04-13  
很好啊,支持你!
2 楼 bylijinnan 2012-03-27  
ershen290 写道
看了你的程序写的不错   支持你  我会常来的

谢谢,欢迎
1 楼 ershen290 2012-03-27  
看了你的程序写的不错   支持你  我会常来的

相关推荐

Global site tag (gtag.js) - Google Analytics