PAT甲级1005 Spell it Right 【20】【字符串操作】

1005 Spell It Right (20分)

题目要求

Given a non-negative integer N, your task is to compute the sum of all the digits of N, and output every digit of the sum in English.
Input Specification:
给出一个非负整数N,你的任务是计算所有N的数位数字之和,然后将这个和的每一个数位都用英语表示出来。

Each input file contains one test case. Each case occupies one line which contains an N (≤10​100​​).
每个测试样例包含一个例子,每个都会将整数N输出到一行里。

Output Specification:
输出要求:

For each test case, output in one line the digits of the sum in English words. There must be one space between two consecutive words, but no extra space at the end of a line.
对于每个测试样例,将数位的和和英文输出到一行,两个单词之间要有一个空格,除此以外,不要输出多余空格。

输入样例:
12345

输出样例:
one five

代码实现:

这是我的代码,用C实现的,始终有两个样例不能过:

#include "stdio.h"

int a[1024];

int main()
{
	int x;
	scanf("%d",&x);//用户输入一个整数x
	
	if(x==0)
	{
		printf("zero");
		return 0;
	}
	
	int sum = 0;
	while(x!=0)//分离数位并计算数位之和 
	{
		sum=sum+x%10;
		x=x/10;
	 } 
	

	int i=0;
	while(sum!=0)
	{
		a[i]=sum%10;
		sum=sum/10;
		i++;
	 } 
	 

	
	for(int j=i-1;j>=0;j--)
	{
		int t=a[j];
		if(t==1)
			printf("one");
		else if(t==2)
			printf("two");
		else if(t==3)
			printf("three");
		else if(t==4)
			printf("four");
		else if(t==5)
			printf("five");
		else if(t==6)
			printf("six");
		else if(t==7)
			printf("seven");
		else if(t==8)
			printf("eight");
		else if(t==9)
			printf("nine");
		else if(t==0)
			printf("zero");
		
		if(j!=0)
			printf(" ");
	}
	return 0;
 } 

这是柳神的代码实现

#include <iostream>
using namespace std;
int main() {
    string a;
    cin >> a;
    int sum = 0;
    for (int i = 0; i < a.length(); i++)  //字符串的操作比数字容易很多
        sum += (a[i] - '0');  //字符和数字的转换通过加减'0'来完成
    string s = to_string(sum);//把和转换为字符串
    string arr[10] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};//看!C++里有字符串数组!
    cout << arr[s[0] - '0'];//单独输出第一个避免多余空格 
    for (int i = 1; i < s.length(); i++)
        cout << " " << arr[s[i] - '0'];
    return 0;
}

C++允许字符串数组的存在,其访问方式见上例子。
此外,这个代码充分体现了柳神在字符串应用上如臂使指的熟练程度,respect!
And I will get there in a near future.

生词

生词翻译
non-negative非负
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值