三进制
内存限制: 256 Mb时间限制: 1000 ms
题目描述
给定一个十进制的正整数 n,请将它转换成三进制表示后输出。
输入格式
- 单个整数:表示 n
输出格式
- 单个整数:表示输入数据的三进制表示
数据范围
- 30% 的数据,1≤n≤20
- 60% 的数据,1≤n≤1000
- 100% 的数据,1≤n≤2,000,000,000
样例数据
输入:
8
输出:
22
解析:短除法转换进制,使用递归输出,详见代码:
#include <bits/stdc++.h>
using namespace std;
void f(int x) {
if (x == 0) return;
int d = x % 3;
f(x / 3);
cout << d;
return;
}
int main() {
int n;
cin >> n;
f(n);
return 0;
}
使用数组记录输出,详见代码:
#include <bits/stdc++.h>
using namespace std;
int a[105];
int main() {
int n;
cin >> n;
int cnt = 0;
while (n > 0) {
cnt++;
a[cnt] = n % 3;
n /= 3;
}
for(int i = cnt; i >= 1; i--) {
cout << a[i];
}
return 0;
}

被折叠的 条评论
为什么被折叠?



