傳送門
https://pintia.cn/problem-sets/994805260223102976/problems/994805324509200384
題目
讀入一個自然數n,計算其各位數字之和,用漢語拼音寫出和的每一位數字。
輸入格式:每個測試輸入包含1個測試用例,即給出自然數n的值。這里保證n小于10100。
輸出格式:在一行內輸出n的各位數字之和的每一位,拼音數字間有1 空格,但一行中最后一個拼音數字后沒有空格。
輸入樣例:
1234567890987654321123456789
輸出樣例:
yi san wu
分析
Java實現方法是:
1.讀入一行字符串,然后將字符串轉為char數組;
2.將char數組的每位轉為int型,這里注意要減去0的ASCII碼為48,然后相加起來;
3.然后將和再轉為char數組,根據每位的數字,輸出對應的拼音即可,需要注意的是最后沒有空格。
C++實現方法與Java類似,這里就不再贅述。
源代碼
//C/C++實現
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <sstream>
using namespace std;
int main(){
char c[102];
gets(c);
int sum = 0;
for(int i = 0; i < strlen(c); i ++){
sum += (c[i] - '0');
}
stringstream ss;
ss << sum;
string s = ss.str();
for(int j = 0; j < s.size(); j ++){
if(s[j] == '0'){
printf("ling");
}
else if(s[j] == '1'){
printf("yi");
}
else if(s[j] == '2'){
printf("er");
}
else if(s[j] == '3'){
printf("san");
}
else if(s[j] == '4'){
printf("si");
}
else if(s[j] == '5'){
printf("wu");
}
else if(s[j] == '6'){
printf("liu");
}
else if(s[j] == '7'){
printf("qi");
}
else if(s[j] == '8'){
printf("ba");
}
else{
printf("jiu");
}
if(j != s.size() - 1){
printf("%c", ' ');
}
}
printf("%c", '\n');
return 0;
}
//Java實現
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String s1 = scanner.next();
char[] c1 = s1.toCharArray();
int sum = 0;
for(int i=0;i<c1.length;i++) {
int n = c1[i] - 48;
sum += n;
}
String s2 = String.valueOf(sum);
char[] c2 = s2.toCharArray();
for(int j=0;j<c2.length;j++) {
if (c2[j] == '1') {
System.out.print("yi");
}
else if (c2[j] == '2') {
System.out.print("er");
}
else if (c2[j] == '3'){
System.out.print("san");
}
else if (c2[j] == '4') {
System.out.print("si");
}
else if (c2[j] == '5') {
System.out.print("wu");
}
else if (c2[j] == '6'){
System.out.print("liu");
}
else if (c2[j] == '7') {
System.out.print("qi");
}
else if (c2[j] == '8') {
System.out.print("ba");
}
else if(c2[j] == '9') {
System.out.print("jiu");
}
else{
System.out.print("ling");
}
if(j < c2.length - 1){
System.out.print(' ');
}
}
}
}