实现两个大数相加

import java.math.*;
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";  
         BigInteger a  = new BigInteger(x);
         BigInteger b = new BigInteger(y);
         BigInteger c = a.add(b);
         System.out.println(c.toString());
         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;
    	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){
    		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){
    	StringBuffer sb = new StringBuffer();
    	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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值