合肥工业大学oj 1342 八进制转十六进制

#include<iostream>
#include<string>
using namespace std;

class Unite{
public:
  string hexS;
  char hex;
  Unite(string hexS, char hex){
    this->hexS = hexS;
    this->hex = hex;
  }
};

string toBinary[]{"000", "001", "010", "011", "100", "101", "110", "111"};
Unite list[]{Unite("0000", '0'), Unite("0001", '1'), Unite("0010", '2'), Unite("0011", '3'),
             Unite("0100", '4'), Unite("0101", '5'), Unite("0110", '6'), Unite("0111", '7'),
             Unite("1000", '8'), Unite("1001", '9'), Unite("1010", 'A'), Unite("1011", 'B'),
             Unite("1100", 'C'), Unite("1101", 'D'), Unite("1110", 'E'), Unite("1111", 'F')};
char binarySearch(string);//使用二分搜索尽可能优化

int main(){
    int t;
    cin >> t;
    while(t--){
        string octS, biS = "", hexS = "";
        cin >> octS;
        for(unsigned int i = 0; i < octS.length(); i++){
          biS += toBinary[octS[i] - '0'];
        }
        int temp = 4 - biS.length() % 4;
        while(temp--) biS = "0" + biS;
        for(unsigned int i = 0; i < biS.length(); i += 4){
          hexS += binarySearch(biS.substr(i, 4));
        }
        while(hexS[0] == '0') hexS.erase(0, 1);
        cout << hexS << endl;
    }
    return 0;
}

char binarySearch(string str){
  int mid, left = 0, right = 15;
  while (left <= right){
    mid = (left + right) / 2;
    if(str == list[mid].hexS) return list[mid].hex;
    else if(str < list[mid].hexS) right = mid - 1;
    else left = mid + 1;
  }
  return '*';//防止非法输入,尽管不会出现非法输入
}

//presented by 大吉大利,今晚AC

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值