Brian Warehouse

Some birds aren`t meant to be caged, their feathers are just too bright... ...
posts - 40, comments - 16, trackbacks - 0, articles - 1

POJ Grids 2798 2进制转化为16进制

Posted on 2010-08-17 14:18 Brian 阅读(296) 评论(0)  编辑 收藏 引用 所属分类: POJ

Description

输入一个2进制的数,要求输出该2进制数的16进制表示。
在16进制的表示中,A-F表示10-15

Input

第1行是测试数据的组数n,后面跟着n行输入。每组测试数据占1行,包括一个以0和1组成的字符串,字符串长度至少是1,至多是10000

Output

n行,每行输出对应一个输入。

Sample Input

2
100000
111

 

 

 

Sample Output

20
7


09小孩问我的一道题,原来写的代码足足有90多行,今天重写:
 
#include <iostream>
#include 
<string>
using namespace std;

int main()
{
    
int n,pos,sec,i,j,w[4= {1,2,4,8}; //sec是分段处理,pos是对应权值位置
    char x[17= "0123456789ABCDEF"//打表        
    string bin; //输入的二进制字符串
    cin>>n;
    
while (n--)
    {
        cin
>>bin;
        sec
=bin.length()%4;
        pos
=0;
        
for (i=sec; i>0; i--)
            
if (bin[sec-i]=='1')
                pos 
+= w[i-1];
        
if (sec) printf("%c",x[pos]);
        
for (i=sec; i<bin.length(); i+=4)
        {
            pos
=0;
            
for (j=0; j<4; j++)
                
if (bin[i+j]=='1')
                    pos 
+= w[3-j];
            printf(
"%c",x[pos]);
        }
        printf(
"\n");
    }
    
return 0;
}

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理