PAT A1005 Spell It Right (20)

PAT A1005 Spell It Right
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:
Each input file contains one test case. Each case occupies one line which contains an N (≤10​100​​).
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.
Sample Input:

12345

Sample Output:

one five

分析:

  1. 写输出循环的时候可以把第一个数据写在外面,然后从下标1开始循环,这样可以省去每个循环里的判断时间
#include <iostream>
#include <string>
using namespace std;
int main() {
  const string num_to_text[] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"};
  int number[105];
  int weishu = 0, sum(0), itemp;
  char ctemp;
  memset(number, 0, sizeof(number));
  while (scanf("%c", &ctemp), ctemp != '\n') {
    itemp = ctemp - '0';
    number[weishu] = itemp;
    weishu++;
  }
  for (int i = 0; i < weishu; i++) {
    sum += number[i];
  }
  char csum[10];
  sprintf(csum, "%d", sum);
  for (int i = 0; i < strlen(csum); i++) {
    cout << num_to_text[csum[i] - '0'];
    if (i < strlen(csum) - 1)
      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');
    string s = to_string(sum);
    string arr[10] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
    cout << arr[s[0] - '0'];
    for (int i = 1; i < s.length(); i++)
        cout << " " << arr[s[i] - '0'];
    return 0;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容