Problem Description
把二进制数转化为十六进制数。
Input
多组测试数据。
每组数据一行,由0和1组成,表示一个二进制的数。
已知输入长度不超过1000000,没有前导0。
每组数据一行,由0和1组成,表示一个二进制的数。
已知输入长度不超过1000000,没有前导0。
Output
转化成对应的十六进制数输出。
Sample Input
10 11111 11101110
Sample Output
2 1F EE
用栈很好做代码如下:
# include <iostream> # include <numeric> # include <algorithm> # include <functional> # include <list> # include <map> # include <set> # include <stack> # include <deque> # include <queue> # include <vector> # include <ctime> # include <cstdlib> # include <cmath> # include <string> # include <cstring> using namespace std; const int maxx = 1000005; int a[maxx] = {0}; int main(int argc, char *argv[]) { char s[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; // cout << pow(2, 0) << endl; string str; while(cin >> str) { memset(a, 0, sizeof(a)); int k = str.size() % 4; int l; int j; if(k == 0) { l = str.size(); j = 0; } else { l = str.size() + 4 - k; j = 4 - k; } // cout << "l = " << l << " ,k = " << k << endl; for(int i = 0; i < str.size(); i++, j++) { a[j] = str[i] - '0'; // cout << "j = " << j << " ," << a[j] << endl; } // for(int i = 0; i < l; i++) // { // cout << "a[" << i << "] = " << a[i] << endl; // } int f = 0; int t = 0; stack<char> ss; for(int i = l - 1; i >= 0; i--) { if(a[i]) { t = t + pow(2, f); // cout << "ttt = " << t << ",i = " << i << endl; } f++; if(f == 4) { // cout << "t = " << t << ",i = " << i << ",s[t] = " << s[t] << endl; ss.push(s[t]); t = 0; f = 0; // cout << "t = " << t << ",f = " << f << endl; } } while(!ss.empty()) { cout << ss.top(); ss.pop(); } cout << endl; } return 0; }