B1002_写出这个数 (20分)
读入一个正整数 n,计算其各位数字之和,用汉语拼音写出和的每一位数字。
输入格式:
每个测试输入包含 1 个测试用例,即给出自然数 n 的值。这里保证 n 小于 10^100
输出格式:
在一行内输出 n 的各位数字之和的每一位,拼音数字间有 1 空格,但一行中最后一个拼音数字后没有空格。
输入样例:
1234567890987654321123456789
输出样例:
yi san wu
第一种方法:栈
#include<string>
#include<stack>
#include<iostream>
using namespace std;
int main() {
int sum = 0;
string s;
cin >> s;
for (unsigned int i = 0; i < s.length(); i++) {
sum += s[i] - '0';
}
stack<string> PinYin;
while (sum) {
int digit = sum % 10;
switch(digit) {
case 0: PinYin.push("ling");break;
case 1: PinYin.push("yi");break;
case 2: PinYin.push("er");break;
case 3: PinYin.push("san");break;
case 4: PinYin.push("si");break;
case 5: PinYin.push("wu");break;
case 6: PinYin.push("liu");break;
case 7: PinYin.push("qi");break;
case 8: PinYin.push("ba");break;
case 9: PinYin.push("jiu");break;
default: break;
}
sum /= 10;
}
for (unsigned int i = 0; i <= PinYin.size() + 1; i++) {
if (i == PinYin.size() + 1) {
cout << PinYin.top();
} else {
cout << PinYin.top() << " ";
}
PinYin.pop();
}
return 0;
}
第二种方法:二维字符数组
#include<cstdio>
#include<cstring>
int main() {
char qtc[110];
gets(qtc);
int len = strlen(qtc);
int sum = 0;
for (int i = 0; i < len; i++) {
sum += qtc[i] - '0'; // 将字符转化为数字并累加
}
int num = 0, ans[10];
while (sum) {
ans[num++] = sum % 10; // 将 sum中的每一位保存在数组中
sum /= 10;
}
char PinYin[10][5] = {"ling", "yi", "er", "san", "si", "wu", "liu", "qi", "ba", "jiu"};
for (int i = num - 1; i >= 0; i--) {
printf("%s", PinYin[ans[i]]); // ans[i]即为高位开始的第i个数字
if (i) printf(" "); // i不为0则空格隔开
else printf("\n");
}
return 0;
}
第三种方法: switch case
#include<stdio.h>
#include<string.h>
int main() {
int sum = 0;
char ch;
ch = getchar();
while (ch != '\n')
{
switch (ch)
{
case '1':
sum += 1;
break;
case '2':
sum += 2;
break;
case '3':
sum += 3;
break;
case '4':
sum += 4;
break;
case '5':
sum += 5;
break;
case '6':
sum += 6;
break;
case '7':
sum += 7;
break;
case '8':
sum += 8;
break;
case '9':
sum += 9;
break;
default:
sum += 0;
break;
}
ch = getchar(); //是继续往下读字符啦
}
char *result[100];
int digit_count = 0;
while(sum != 0)
{
int digit = sum % 10;
switch (digit)
{
case 0:
result[digit_count] = "ling";
break;
case 1:
result[digit_count] = "yi";
break;
case 2:
result[digit_count] = "er";
break;
case 3:
result[digit_count] = "san";
break;
case 4:
result[digit_count] = "si";
break;
case 5:
result[digit_count] = "wu";
break;
case 6:
result[digit_count] = "liu";
break;
case 7:
result[digit_count] = "qi";
break;
case 8:
result[digit_count] = "ba";
break;
case 9:
result[digit_count] = "jiu";
break;
default:
break;
}
sum = sum / 10;
digit_count++;
}
for (int i = digit_count - 1; i >= 0; i--) {
if (i == 0) {
printf("%s", result[i]);
} else {
printf("%s ", result[i]);
}
}
return 0;
}