AcWing 3616. 进制转换
原题链接
简单
作者:
sky-koi
,
2024-11-17 22:18:09
,
所有人可见
,
阅读 3
算法1
C++ 代码
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int stack[35];
int top;
int main() {
string s;
cin >> s;
int res = 0;
for (int i = 0; i < s.size(); i++) {
int a;
if (s[i] >= '0' && s[i] <= '9')
a = s[i] - '0';
else
a = s[i] - 'a' + 10;
if (i < s.size()) {
cout << a << " ";
} else {
cout << a;
}
res += a * pow(12, s.size() - i - 1);
}
cout << endl << res << endl;
while (res) {
stack[top++] = res % 2;
res /= 2;
}
for (int i = top; i <= 31; i++) {
stack[i] = 0;
}
int index = 0;
for (int i = 31; i >= 0; i--) {
cout << stack[i];
index++;
if (index == 8) {
cout << " ";
index = 0;
}
}
return 0;
}
算法2
stoi函数
C++ 代码
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int stack[35];
int top;
int main() {
string s;
cin >> s;
for (int i = 0; i < s.size(); i++) {
int x;
if (s[i] >= 'a' && s[i] <= 'b') {
x = 10 + s[i] - 'a';
} else {
x = s[i] - '0';
}
cout << x << " ";
}
cout << endl;
int res = stoi(s, nullptr, 12); // 十进制数
cout << res << endl;
for (int i = 0; i < 32; i++)
{
stack[i] = res & 1;
res >>= 1;
}
for(int i = 31, j = 0;i >= 0; i--)
{
cout<<stack[i];
j++;
if(j == 8)
{
cout << " ";
j = 0;
}
}
cout << endl;
return 0;
}