题解 | #缩短二进制#-自己用C++实现进制转换
缩短二进制
https://www.nowcoder.com/practice/4ffcc9f206b949ddb057ee0099b34d51
用C++代码自己实现了一遍,看了题解,啊这么简单。不过锻炼一下进制转换的代码:
#include <iostream>
#include <vector>
using namespace std;
vector<char> dec2hex(int dec)
{
vector<char> a;
vector<char> b;
char temp;
int re = dec % 16;
while (re != 0)
{
temp = (re >= 0 && re <= 9) ? ((char)(re + 48)) : ((char)(re + 55));
a.push_back(temp);
dec = dec / 16;
re = dec % 16;
}
int n = a.size();
int i = n - 1;
while (i >= 0)
{
if (((n - i - 1) == 0) && (a[i] == '0'))
{
--i;
continue;
}
b.push_back(a[i]);
--i;
}
return b;
}
vector<char> dec2oct(int dec)
{
vector<char> a;
vector<char> b;
char temp;
int re = dec % 8;
while (re != 0)
{
temp = (char)(re + 48);
a.push_back(temp);
dec = dec / 8;
re = dec % 8;
}
int n = a.size();
int i = n - 1;
while (i >= 0)
{
if (((n - i - 1) == 0) && (a[i] == '0'))
{
--i;
continue;
}
b.push_back(a[i]);
--i;
}
return b;
}
int main()
{
int a = 1234;
vector<char> a_hex = dec2hex(a);
vector<char> a_oct = dec2oct(a);
cout << "0";
for (auto c : a_oct)
cout << c;
cout << " 0X";
for (auto c : a_hex)
cout << c;
}
题解的核心:
-
printf("%#o %#X\n", val, val);
-
cout.setf(ios::showbase | ios::uppercase);
cout << oct << val << " " << hex << val << endl;
C++题解 文章被收录于专栏
记录在牛客网用C++刷题的题解思路