蓝桥杯 adv239 P0102

蓝桥杯 adv239 P0102

题目描述

用户输入三个字符,每个字符取值范围是0-9,A-F。然后程序会把这三个字符转化为相应的十六进制整数,并分别以十六进制,十进制,八进制输出,十六进制表示成3位,八进制表示成4位,若不够前面补0。(不考虑输入不合法的情况)

输入

1D5

输出

(注意冒号后面有一个空格)

Hex: 0x1D5 Decimal: 469 Octal: 0725

参考解答

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <string>

using namespace std;

int toInt(string s) {
int sum = 0;
for (int i = 0; i < 3; i++) {
if (s[i] >= '0' && s[i] <= '9')
sum = sum * 16 + (s[i] - '0');
else
sum = sum * 16 + (s[i] - 'A' + 10);
}
return sum;
}

int main() {
string s, oct;
int t, dec;
cin >> s;
t = dec = toInt(s);
while (t) { // 转 8 进制
oct = (char)(t % 8 + '0') + oct;
t /= 8;
}
cout << "Hex: 0x" << s << endl;
cout << "Decimal: " << dec << endl;
cout << "Octal: ";
// string res(4-oct.length(), '0')
cout.fill('0'); // 一直有效
cout.width(4); // 下一次有效
cout << oct;
// cout << res << oct;
return 0;
}

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×