AcWing 3395. 10进制 VS 2进制
原题链接
中等
#include <bits/stdc++.h>
using namespace std;
int t, n, m, k, l, r, op, x, y;
string str, tmp;
const int siz = 4e3 + 10;
struct bn {
public :
int l ;
char d[siz];
bn() {
l = 0;
}
bn(const bn& b) {
l = b.l;
memcpy(d, b.d, l);
};
bn operator/(const int &x) {
bn res;
int cu = 0;
bool flag = false;
for (int i = l - 1; i >= 0; i--) {
cu = cu * 10 + d[i];
if (cu / x) {
flag = true;
res.d[res.l++] = cu / x;
cu %= x;
} else {
if(flag)res.d[res.l++] = 0;
}
}
reverse(res.d, res.d + res.l);
return res;
}
bn operator+(const bn&b) {
bn res;
int mx = max(l, b. l), cy = 0;
res.l = mx;
for (int i = 0; i < mx; i++) {
res.d[i] = (i < l ? d[i] : 0) + (i < b.l ? b.d[i] : 0) + cy;
cy = res.d[i] / 10;
res.d[i] %= 10;
}
if (cy) res.d[res.l++] = cy;
return res;
}
bn operator *(const int & x) {
bn res(*this);
int cy = 0;
for (int i = 0; i < l; i++) {
res.d[i] = res.d[i] * x + cy;
cy = res.d[i] / 10;
res.d[i] %= 10;
}
while (cy) {
res.d[res.l++] = cy % 10;
cy /= 10;
}
return res;
}
int operator % (const int & x) {
int cu = 0;
for (int i = l - 1; i >= 0; i--) {
cu = cu * 10 + d[i];
if (cu / x)cu %= x;
}
return cu;
}
void operator = (const bn&b) {
l = b.l;
memcpy(d, b.d, l);
}
void set(string str) {
l = str.size();
for (int i = 0; i < l; i++) {
d[i] = str[l - i - 1] - '0';
}
}
void print() {
bool flag = false;
for (int i = l - 1; i >= 0; i--) {
if(d[i])flag=true;
if(flag)
cout << (int)d[i];
}
cout << "\n";
}
bool empty() {
return l == 0;
}
};
bn b1, b2, b3, jc[siz];
void solve() {
cin >> str;
b1.set(str);
while (!b1.empty()) {
tmp.push_back('0' + b1 % 2);
b1 = b1 / 2;
}
reverse(tmp.begin(), tmp.end());
b2.set(tmp);
l = b2.l;
jc[0].l = 1,jc[0].d[0] = 1;
for (int i = 1; i < l; i++) {
jc[i] = jc[i - 1] * 2;
}
for(int i = 0;i<l;i++){
b3 = b3 + jc[l-i-1] * b2.d[i];
}
b3.print();
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
solve();
return 0;
}