PAT题目分析

PAT A1005 Spell It Right (20)

2019-03-17  本文已影响0人  ranerr_

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;
}
上一篇下一篇

猜你喜欢

热点阅读