Posted on 2010-08-17 14:18
Brian 閱讀(325)
評論(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;
}