2 条题解
信息
- ID
- 223
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 6
- 标签
- 递交数
- 425
- 已通过
- 130
- 上传者
数据结构与算法 第二章栈与队列 c++
#include <iostream>
#include <stack>
using namespace std;
int main()
{
int n;
while(cin>>n){
int sum=0;
stack<int>v;
while(n>0){
sum++;
v.push(n%3);
n/=3;
}
for(int i=0;i<sum;i++){
cout<<v.top();
v.pop();
}
cout<<endl;
}
return 0;
}
这个改进一些
#include <iostream>
#include <stack>
using namespace std;
int main()
{
int n;
while (cin >> n) {
stack<int>v;
while (n > 0)
v.push(n % 3);
n /= 3;
}
while(v.size()) {
cout << v.top();
v.pop();
}
cout << endl;
}
return 0;
}
#define M 100
typedef struct {
int da[M];
int top;
} St;
void cs(St* s) {
s->top = -1;
}
void push(St* s, int v) {
s->top++;
s->da[s->top] = v;
}
void pop(St* s, int* v) {
*v = s->da[s->top];
s->top--;
}
void peek(St* s, int* v) {
*v = s->da[s->top];
}
int main() {
int a;
while (scanf("%d", &a) != EOF) {
St s;
cs(&s);
int cnt = 0;
while (a > 0) {
cnt++;
push(&s, a % 3);
a /= 3;
}
for (int i = 0; i < cnt; i++) {
int v1, v2;
peek(&s, &v1);
printf("%d", v1);
pop(&s, &v2);
}
printf("\n");
}
return 0;
}