PAT 乙级 1002.写出这个数 C++/Java

时间:2023-02-03 16:51:14

1002 写出这个数 (20 分)

题目来源

读入一个正整数 n,计算其各位数字之和,用汉语拼音写出和的每一位数字。

输入格式:

每个测试输入包含 1 个测试用例,即给出自然数 n 的值。这里保证 n 小于 $10^{100}$

输出格式:

在一行内输出 n 的各位数字之和的每一位,拼音数字间有 1 空格,但一行中最后一个拼音数字后没有空格。

输入样例:

1234567890987654321123456789

输出样例:

yi san wu

C++实现:

分析:

因为数字的范围是小于$10^{100}$,所以要用string接收输入,将string中的每一位数字累加到sum里,用 to_string(sum) 将sum转化成字符串nums,然后逐一输出nums对应的拼音

 #include <iostream>
#include <string>
using namespace std; int main()
{
string str;
string output[] = { "ling","yi","er","san","si","wu","liu","qi","ba","jiu" };
int sum = ; cin >> str;
int length = str.length(); for (int i = ; i < length; ++i)
{
sum = sum + str[i] - '';
} string nums = to_string(sum); for (int i = ; i < nums.length(); ++i)
{
if (i != )
{
cout << " ";
}
cout << output[nums[i] - ''];
} return ;
}

另解:

利用栈后进先出(FILO)的特点

同样用string接收输入,将string中的每一位数字累加到sum里,接着将sum的每一位数字保存到栈中,然后进行出栈的操作,输出对应的拼音

假定sum = 135,那么入栈的顺序就是(栈底)5 3 1(栈顶),出栈的顺序就是1 3 5

 #include <iostream>
#include <string>
#include <stack>
using namespace std; int main()
{
string str;
string output[] = { "ling","yi","er","san","si","wu","liu","qi","ba","jiu" };
stack<int> v;
int sum = ; cin >> str;
int length = str.length(); for (int i = ; i < length; ++i)
{
sum = sum + str[i] - '';
}
//
while (sum != )
{
v.push(sum % );
sum /= ;
}
cout << output[v.top()];
v.pop();
while (!v.empty())
{
cout << " " << output[v.top()];
v.pop();
}
return ;
}

Java实现:

 import java.util.Scanner;

 public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = input.nextLine();
int num = 0;
for (int i = 0; i < str.length(); i++) {
num += str.charAt(i) - '0';
}
String s = String.valueOf(num);
String[] output = {"ling","yi", "er", "san", "si", "wu", "liu", "qi", "ba", "jiu"};
for (int i = 0; i < s.length(); i++) {
num = s.charAt(i) - '0';
if (i != 0)
System.out.print(" ");
System.out.print(output[num]);
}
}
}