`
endual
  • 浏览: 3509362 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

两个正整数相加

 
阅读更多

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

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

就这么做下去。

 

 

但是遇到了,如果是有符号的整数就麻烦了,相当于负数+整数是减法了,呵呵,又要重新做过了。

 

有没有更好的办法呢 ??

 

 

 

 

 

 

 

 

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics