对称三进制

catting123 / 2023-08-20 / 原文

题目背景

进制转换公式

\[x=\sum_{i=0}^{n-1}{a_i \times p^i} \]

\(i\) 是从右往左数的位数,从第 \(0\) 位开始。

对称三进制转十进制

输入输出:

代码:

#include<iostream>
#include<cstring>

using namespace std;
int n, p[107], ans;
char s[107];

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);
    cin >> n;
    p[0] = 1;
    for (int i = 1; i <= 100; i++) {
        p[i] = p[i - 1] * 3;
    }
    while (n--) {
        cin >> s;
        ans = 0;
        int len = strlen(s);
        for (int i = len - 1; i >= 0; i-- ) {
            if (s[i] == '1') {
                ans += p[len - 1 - i];
            } else if (s[i] == '-') {
                ans -= p[len - 1 - i];
            }
        }
        cout << ans << "\n";
    }
    return 0;
}

十进制转对称三进制

输入输出:

代码:

#include<iostream>
#include<cstring>
#include<algorithm>
#include<vector>
#include<map>
using namespace std;
const int N = 50;
int num[N], n, x;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);
    cin >> n;
    while (n--) {
        cin >> x;
        memset(num, 0, sizeof(num));
        int flag = 1, cnt = 0;
        if (x < 0) {
            flag = -1;
            x = -x;
        }
        if (x == 0) {
            cout << x << "\n";
            continue;
        }
        while (x) {
            num[cnt++] = x % 3;
            x = x / 3;
        }
        for (int i = 0; i < cnt; i++) {
            if (num[i] == 2) {
                num[i] = -1;
                num[i + 1]++;
            } else if(num[i] == 3) {
                num[i] = 0;
                num[i + 1]++;
            }
        }
        if (num[cnt]) {
            cnt++;
        }
        if (flag == -1) {
            for (int i = cnt - 1; i >= 0; i--) {
                num[i] = -num[i];
            }
        }
        for (int i = cnt - 1; i >= 0; i--) {
            if (num[i] == -1) {
                cout << "-";
            } else {
                cout << num[i];
            }
        }
        cout << "\n";
    }
    return 0;
}