文章

454

粉丝

0

获赞

1

访问

10.6k

头像
A + B 加强版 题解(四语言 AC 代码)
P1323 浙江大学机试题
发布于 2026年11月
阅读数 14

题意

A、B 的每一位用英文单词给出(zero~nine),按 A + B = 的形式读入,求 A+B 的值。

思路

  • 把 "+" 之前的单词按 zero~nine 映射成数字并拼接成 A(支持多位数,如 three four = 34),"+" 之后到 "=" 之前同理得到 B。

  • 按 token 读入,遇到 "=" 结束本组;A 与 B 同时为 0 时输入结束且不输出。

  • 多组数据逐行输出 A+B。

复杂度

时间 O(L),空间 O(1)。

参考代码(C / C++ / Java / Python)

C:

#include <stdio.h>
#include <string.h>
int val(const char*w){
static const char*n[]={"zero","one","two","three","four","five","six","seven","eight","nine"};
for(int i=0;i<10;i++)if(strcmp(w,n[i])==0)return i;
return 0;}
int main(void){
char t[16];
while(scanf("%s",t)==1){
int a=0,b=0;
a=val(t);
while(scanf("%s",t)==1&&strcmp(t,"+")!=0)a=a*10+val(t);
b=0;
while(scanf("%s",t)==1&&strcmp(t,"=")!=0)b=b*10+val(t);
if(a==0&&b==0)break;
printf("%d\n",a+b);}
return 0;}

C++:

#include <iostream>
#include <string>
#include <map>
using namespace std;
int main(){
map<string,int> M;
string n[10]={"zero","one","two","three","four","five","six","seven","eight","nine"};
for(int i=0;i<10;i...
登录查看完整内容


登录后发布评论

暂无评论,来抢沙发