我的PAT-BASIC代码仓:https://github.com/617076674/PAT-BASIC
原题链接:https://pintia.cn/problem-sets/994805260223102976/problems/994805324509200384
题目描述:
知识点:字符串
本题所给的自然数n很大,我们采用字符串的形式接收。遍历字符串中的每一个字符,累加即得总和。
由于题目规定了n最多就100位数,因此累加得到的总和一定小于900。所以我们可以用int型的变量接收即可。
根据映射规则建立一个数组来处理所得总和,输出结果。
时间复杂度是O(m),其中m为输入自然数n的位数。空间复杂度是O(1)。
C++代码:
#include
#include
#include
using namespace std;
int main() {
string strings[] = { "ling", "yi", "er", "san", "si", "wu", "liu", "qi", "ba", "jiu"};
string n;
cin >> n;
int sum = 0;
for (int i = 0; i < n.length(); i++) {
sum += n[i] - '0';
}
vector temp;
while (sum > 0) {
temp.push_back(sum % 10);
sum /= 10;
}
for (int i = temp.size() - 1; i >= 0; i--) {
cout << strings[temp[i]];
if (i != 0) {
cout << " ";
}
}
}
C++解题报告:
JAVA代码:
import java.util.Scanner;
import java.util.Stack;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
int sum = 0;
for (int i = 0; i < input.length(); i++) {
sum += input.charAt(i) - '0';
}
String[] numbers = {"ling", "yi", "er", "san", "si", "wu", "liu", "qi", "ba", "jiu"};
Stack stack = new Stack<>();
while(sum > 0){
int num = sum % 10;
sum /= 10;
stack.push(num);
}
StringBuilder stringBuilder = new StringBuilder();
while(!stack.isEmpty()){
stringBuilder.append(numbers[stack.pop()]);
stringBuilder.append(" ");
}
System.out.println(stringBuilder.substring(0, stringBuilder.length() - 1));
}
}
JAVA解题报告:
Bash Shell代码:
# !/bin/bash
read input
sum=0
digits=("ling" "yi" "er" "san" "si" "wu" "liu" "qi" "ba" "jiu")
for (( i = 0; i < ${#input}; i++ ));
do
sum=$(expr $sum + ${input:${i}:1})
done
for (( i = 0; i < ${#sum}; i++));
do
echo -e "${digits[${sum:${i}:1}]}\c"
if [ $i -ne $(expr ${#sum} - 1) ]
then
echo -e " \c"
fi
done
Bash Shell解题报告: