0
点赞
收藏
分享

微信扫一扫

清华大学上机题--进制转换

转角一扇门 2022-03-11 阅读 117
c++

进制转换

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

void div(vector<int> &v) {
    vector<int> c;
    int r = 0;
    for (int i = 0; i < v.size(); i++) {
        r = r * 10 + v[i];
        c.push_back(r / 2);
        r %= 2;
    }
    reverse(c.begin(), c.end());
    while (c.size() > 1 && c.back() == 0) c.pop_back();
    reverse(c.begin(), c.end());
    v = c;
}

int main() {
#ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
#endif
    string str;
    while (cin >> str) {
        vector<int> num;
        for (int i = 0; i < str.length(); i++) {
            num.push_back(str[i] - '0');
        }
        string ans = "";
        while (num[0] != 0) {
//            for (int i = 0; i < num.size(); i++)
//                cout << num[i];
//            cout << endl;
            int x = num[num.size() - 1];
            ans = char(x % 2 + '0') + ans;
            div(num);
        }
        if (str == "0") cout << str << endl;
        else cout << ans << endl;
    }
    return 0;
}
举报

相关推荐

0 条评论