天天看點

兩個正整數相加

import java.util.Scanner;
import java.util.Stack;

public class T {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		Scanner cin = new Scanner(System.in);
		String a, b;
		a = cin.next();
		b = cin.next();
		
		char f1 = a.charAt(0) ;
		char f2 = b.charAt(0) ;

		if(a.length() < b.length()) {
		
			String temp = a ;
			a = b ;
			b = temp ;
			
		}
		
		
		
		// TODO Auto-generated method stub
		Stack stacka = new Stack();
		Stack stackb = new Stack();
		String ab = a;
		System.out.println("-----a-------" +ab);
		while (ab.length() != 0) {
			
			char c = ab.charAt(0);
			String subab = ab.substring(1);
			stacka.push(c) ;
			ab = subab ;
		}
		
		String abc = b;
		System.out.println("-----b-------" +abc);
		while (abc.length() != 0) {
			
			char c = abc.charAt(0);
			String subabc = abc.substring(1);
			stackb.push(c) ;
			abc = subabc ;
		}

		Stack sum = new Stack();
		int temp = 0;
		int t = 0;
		while (!stacka.isEmpty() && !stackb.isEmpty()) { // 如果兩個裡面其中有一個是空了,那麼停止

			int aInt = Integer.parseInt(stacka.pop().toString());
			int bInt = Integer.parseInt(stackb.pop().toString());
			temp = aInt + bInt + t;
			if (temp < 10) {
				sum.push(temp);
				t = 0;
			} else {

				String tempS = temp + ""; // 将temp轉換成String類型,此時是兩位數sumAB 10-19
				t = 1; // 将t設定成為1,此時将sumAB的1取得
				char c1 = tempS.charAt(1); // 取得sumAB的個位數
				temp = Integer.parseInt(c1 + ""); // 将個位數轉換成int類型指派給temp
				sum.push(temp); // 添加到棧中去
			}

		}// end while ;



	while(!stacka.isEmpty()) {
		
		int aInt = Integer.parseInt(stacka.pop().toString());
		temp = aInt + t;
		if (temp < 10) {
			sum.push(temp);
			t = 0;
		} else {

			String tempS = temp + ""; // 将temp轉換成String類型,此時是兩位數sumAB 10-19
			t = 1; // 将t設定成為1,此時将sumAB的1取得
			char c1 = tempS.charAt(1); // 取得sumAB的個位數
			temp = Integer.parseInt(c1 + ""); // 将個位數轉換成int類型指派給temp
			sum.push(temp); // 添加到棧中去
		}
		
	}
	if(t==1) {
		
		sum.push(t+"") ;
	}
	String s = "" ;
	while (!sum.isEmpty()) { // 如果兩個裡面其中有一個是空了,那麼停止

		s = s+sum.pop().toString();
		
	}
	System.out.println(s);
		} //end main
} //end clsss
           

今天在杭電的ACM上寫第一題,确實是考研人智慧的。想法非常重要,雖然還沒用做出來,但是算是想法出來了。思路是這樣的,模拟人的做法。

1.輸入字元串a,将字元一個一個的壓入到棧A中

2.輸入字元串b,将字元串一個一個的壓入到棧B中

3.從A中和B中分别彈出一個出來相加為K

4.如果如果K<10,那麼壓入到棧Sum中,如果K>10,那麼将0壓入到棧中,1保留。判斷兩個棧是不是為空。

5.goto 3,并且将結果加上1

。。。。。。。。。。。。。。。。

就這麼做下去。

但是遇到了,如果是有符号的整數就麻煩了,相當于負數+整數是減法了,呵呵,又要重新做過了。

有沒有更好的辦法呢 ??