链接:http://poj.grids.cn/practice/2798/
题目:
- 总时间限制:
- 1000ms
- 内存限制:
- 65536kB
- 描述
- 输入一个2进制的数,要求输出该2进制数的16进制表示。
在16进制的表示中,A-F表示10-15- 输入
- 第1行是测试数据的组数n,后面跟着n行输入。每组测试数据占1行,包括一个以0和1组成的字符串,字符串长度至少是1,至多是10000
- 输出
- n行,每行输出对应一个输入。
- 样例输入
2 100000 111- 样例输出
20 7
代码:
1 #include <iostream> 2 #include <cstdlib> 3 #include <cstdio> 4 #include <cstring> 5 using namespace std; 6 const int MAX = 10000; 7 //char index[] = "0123456789ABCDEF"; 8 //char index[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; 9 char mindex[] = "0123456789ABCDEF"; 10 int main() 11 { 12 //freopen("F:\\input.txt","r",stdin); 13 14 int n; 15 cin>>n; 16 17 char chs[MAX + 1],res[(MAX+3) / 4 + 1]; 18 int length,head_len; 19 int value; 20 while(n--) 21 { 22 cin>>chs; 23 length = strlen(chs); 24 25 //head 26 head_len = length % 4; 27 if(head_len == 0) head_len = 4; 28 value = 0; 29 for(int i = 0; i < head_len; i++) value = value * 2 + (chs[i] - '0'); 30 res[0] = mindex[value]; 31 32 //others 33 int start; 34 int j = 1; 35 36 for(int i = head_len; i < length; i += 4) 37 { 38 value = (chs[i]-'0') * 8 + (chs[i + 1] - '0') * 4 + (chs[i + 2] - '0') * 2 + (chs[i + 3] - '0'); 39 res[j++] = mindex[value]; 40 } 41 42 res[j] = '\0'; 43 cout<<res<<endl; 44 } 45 46 return 0; 47 }
思路:
1.数组使用index无法通过编译
2.长度大,不能使用2--》10--》16的思路,2--》16刚好是倍数,简化了计算