首页 > ACM题库 > 九度OJ > 九度-1010-A + B[解题代码]
2013
12-12

九度-1010-A + B[解题代码]

题目来源:2005年浙江大学计算机及软件工程研究生机试真题

题目描述:
读入两个小于100的正整数A和B,计算A+B.
需要注意的是:A和B的每一位数字由对应的英文单词给出.
输入:
测试输入包含若干测试用例,每个测试用例占一行,格式为"A + B =",相邻两字符串有一个空格间隔.当A和B同时为0时输入结束,相应的结果不要输出.
输出:
对每个测试用例输出1行,即A+B的值.
样例输入:
one + two =
three four + five six =
zero seven + eight nine =
zero + zero =
样例输出:
3
90
96

cpp 代码如下:
#include <stdio.h>
#include <string.h>
char arr[10][8] = { "zero","one","two","three","four","five","six","seven","eight","nine"};
int find(char* str) {
	int i;
	for (i = 0; i <= 10; i++) {
		if (strcmp(arr[i], str) == 0)
			return i;
	}
	return 0;
}
int main() {
	char temp[8];
	while (scanf("%s", temp) != EOF) {
		int a = find(temp);
		scanf("%s", temp);
		if (temp[0] != '+') {
			a = a * 10 + find(temp);
			scanf("%s", temp);
		}
		scanf("%s", temp);
		int b = find(temp);
		scanf("%s", temp);
		if (temp[0] != '=') {
			b = b * 10 + find(temp);
			scanf("%s", temp);
		}
		if(a==0 && b==0)
			break;
		printf("%d\n", a + b);
	}
	return 0;
}
/**************************************************************
	Problem: 1010
	User: coder
	Language: C
	Result: Accepted
	Time:0 ms
	Memory:912 kb
****************************************************************/

java 代码如下:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Scanner;
import java.util.Stack;


public class Main{

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String str;
		String[] ss = {"zero","one","two","three","four","five","six","seven","eight","nine"};
		HashMap<String,Integer> hm = new HashMap<String,Integer>();
		for(int i=0; i<10; i++){
			hm.put(ss[i], i);
		}
		
		while(!(str=br.readLine()).startsWith("zero + zero ")){
			Scanner s = new Scanner(str);
			Stack<String> stack = new Stack<String>();
			while(s.hasNext()){
				stack.push(s.next());
			}
			stack.pop();
			String num_str;
			int num1=0,num2=0;
			for(int i=0;!(num_str=stack.pop()).equals("+");i++ ){
				int temp = hm.get(num_str);
				for(int j=0; j<i; j++)
					temp  *= 10;
				num2 += temp;
			}
			for(int i=0;!stack.isEmpty();i++){
				int temp = hm.get(stack.pop());
				for(int j=0; j<i; j++)
					temp  *= 10;
				num1 += temp;
			}
			System.out.println(num1 + num2);
			
		}
	}

}

/**************************************************************
	Problem: 1010
	User: coder
	Language: Java
	Result: Accepted
	Time:180 ms
	Memory:17048 kb
****************************************************************/


  1. 很高兴你会喜欢这个网站。目前还没有一个开发团队,网站是我一个人在维护,都是用的开源系统,也没有太多需要开发的部分,主要是内容整理。非常感谢你的关注。

  2. Excellent Web-site! I required to ask if I might webpages and use a component of the net web website and use a number of factors for just about any faculty process. Please notify me through email regardless of whether that would be excellent. Many thanks