百练 2798 2进制转化为16进制 解题报告

链接: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刚好是倍数,简化了计算

转载于:https://www.cnblogs.com/mobileliker/archive/2013/05/24/3096393.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值