START:

我就是个铁憨憨。

题目

给出一个不大于10^100 的数字,计算出每一位的和,并将和逐位按英文输出。

思考

  • 这道题不是大数题,但是存储肯定超过 long long int 的范围了,所以应当用字符串来保存。
  • 求余之后将结果入栈,输出的时候就无需考虑顺序了。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <string>
#include <vector>
#include <stack>
using namespace std;

string print1[10] = { "zero","one","two","three","four","five","six","seven","eight","nine" };
int main()
{
string a;
cin >> a;

int c = 0;
int size = a.size();
for (int i = 0; i < size; i++)
{
switch (a[i])
{
case '1':c += 1; break;
case '2':c += 2; break;
case '3':c += 3; break;
case '4':c += 4; break;
case '5':c += 5; break;
case '6':c += 6; break;
case '7':c += 7; break;
case '8':c += 8; break;
case '9':c += 9; break;
default:break;

}
}
stack<int> s;

while (c > 10) {
int d;
d = c % 10;
s.push(d);
c /= 10;

}
s.push(c);
int front1 = s.top();
s.pop();
cout << print1[front1];
while (!s.empty())
{
int front = s.top();
s.pop();
cout << " " << print1[front];
}
return 0;
}

思考

  • 求余的时候,最开始想靠减来实现去掉后面的尾数,但是并不会右移。我写的时候用 c > 10 判断是明显不合理的。

  • 不要太喜欢偷懒,搞出来输出的时候用switch-case语句,要判断的类型是int还用case '1'来判断。

END

相关文章
评论
分享
Please check the post_relate setting in config.yml of hexo-theme-Annie! You should make sure 'postsEnable == true' and the number of site posts greater than 1.
Please check the comment setting in config.yml of hexo-theme-Annie!