1. 程式人生 > >(java) 大數相加 A+B

(java) 大數相加 A+B

java對於大數有BigInteger和BigDecimal;本題用字串進行操作。

 

import java.util.*;
public class Main {
	
	public static void main(String[] args)
	{
		Scanner scanner = new Scanner(System.in);
		int n = scanner.nextInt();
		
		for(int i=0;i<n;i++){
			StringBuffer s1 = new StringBuffer(scanner.next()).reverse();
			StringBuffer s2 = new StringBuffer(scanner.next()).reverse();
			StringBuffer res = new StringBuffer();

			int len1 = s1.length();
			int len2 = s2.length();
			int len;
			if(len1<len2){
				len = len2;
				int cnt = len2-len1;
				while(cnt-->0){
					s1.append('0');
				}
			}
			else{
				len = len1;
				int cnt = len1-len2;
				while(cnt-->0){
					s2.append('0');
				}
			}
			int overflow=0;
			int num;
			for(int j=0;j<len;j++){
				num=s1.charAt(j)-'0'+s2.charAt(j)-'0'+overflow;
				if(num>=10){
					num=num-10;
					overflow=1;
				}
				else{
					overflow=0;
				}
				res.append(String.valueOf(num));
			}
			if(overflow==1){
				res.append(1);
			}
			
			for(int k=s1.length()-1;;k--){
				if(s1.charAt(k)=='0'){
					s1.deleteCharAt(k);
				}
				else break;
			}
			for(int k=s2.length()-1;;k--){
				if(s2.charAt(k)=='0'){
					s2.deleteCharAt(k);
				}
				else break;
			}
			
			System.out.println("Case"+" "+(i+1)+":");
			System.out.println(s1.reverse().toString()+" + "+s2.reverse().toString()+" ="+" "+res.reverse().toString());
			if(i!=n-1){
				System.out.println();
			}
		}

		
	}
}