1. 程式人生 > >大整數相加java實現

大整數相加java實現

package test;

public class MaxIntSum {
	public static void main(String[] args) {
		String a="199999999999999999999999999999999";
		String b="10";
		int max=a.length()>=b.length()?a.length():b.length();
		int []ch_a=new int[max+1];
		int []ch_b=new int[max+1];
		
		int []ch_c=new int[max+1];
		
		for (int i = 0; i < max; i++) {
			int k=max+1-a.length();
//			System.out.println(Integer.parseInt(a.charAt(i)+""));
			try {
//				System.out.println(Integer.parseInt(b.charAt(i)+""));
				ch_a[k+i]=Integer.parseInt(a.charAt(i)+"");
			} catch (StringIndexOutOfBoundsException e) {
				// TODO: handle exception
			}
			
			k=max+1-b.length();
			try {
//				System.out.println(Integer.parseInt(b.charAt(i)+""));
				ch_b[k+i]=Integer.parseInt(b.charAt(i)+"");
			} catch (StringIndexOutOfBoundsException e) {
				// TODO: handle exception
			}
		}
		
		for (int c : ch_a) {
			System.out.print(c);
		}
		System.out.println();
		for (int c : ch_b) {
			System.out.print(c);
		}
		
		for (int i = ch_c.length-1; i >=0 ; i--) {
			if(ch_a[i]+ch_b[i]>9&&i>0){
				ch_a[i-1]+=1;
			}
			ch_c[i]=(ch_a[i]+ch_b[i])%10;
			
		}
		
		System.out.println();
		
		for (int i = 0; i < ch_c.length; i++) {
			if(i==0&&ch_c[i]==0){
				
			}else{
				System.out.print(ch_c[i]);
			}
			
		}
		
		

		
		
		
	}

}