題目敘述
請設計一個程式,此程式可以不斷地輸入一個 N 的值,N 最大可以到1000位數,當N<=0時則離開程式,請將此整數N反轉並輸出(輸出的整數第一個數字不能為零,即反轉後的整數開頭為零的數字皆不輸出,直到第一個非零數字出現之後,才可以輸出零),此外,並請輸出此整數每一個數字的總和。
答題思路
略
參考答案
解法一
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
#include <stdio.h>
#include <string.h>
int main() {
char string[1000];
while(scanf("%s", string) != EOF && string[0] >= '0') {
int total = 0, i = 0, j = strlen(string) - 1;
while(string[i] == '0') i++;
while(string[j] == '0') j--;
for(; j >= i; j--) {
printf("%c", string[j]);
total += string[j] - '0';
}
printf(" %dn", total);
}
return 0;
}
|
解法二
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int main() {
string str;
while(cin >> str and str[0] >= '0') {
int total = 0;
str.erase(0, str.find_first_not_of('0'));
reverse(str.begin(), str.end());
str.erase(0, str.find_first_not_of('0'));
for(char &x: str) total += x - 48;
if (total != 0) cout << str << " " << total << endl;
}
return 0;
}
|