#include "stdio.h" #include "string.h" #include "string" #include "iostream" #include "math.h" #include "map" #include "queue" #include "malloc.h" using namespace std; map<char,string> mp; int main() { mp['0']="0000";mp['1']="0001";mp['2']="0010";mp['3']="0011";mp['4']="0100"; mp['5']="0101";mp['6']="0110";mp['7']="0111";mp['8']="1000";mp['9']="1001"; mp['A']="1010";mp['B']="1011";mp['C']="1100";mp['D']="1101";mp['E']="1110"; mp['F']="1111"; int a; char test[100005]; cin >> a; while(a--) { memset(test,0,sizeof(test)); string b=""; cin>>test; for(int i = 0;i < strlen(test);i++) { b += mp[test[i]]; } int len = b.length(); if(len%3==1) b = "00" + b; else if(len%3==2) b = "0" + b; int flag = 0; for(int i = 0 ;i < b.length(); i = i + 3) { int num = 4*(b[i]-'0')+2*(b[i+1]-'0')+(b[i+2]-'0'); if(num) flag = 1; if(flag) cout<<num; } cout<<endl; } return 0; }
但是这个跑在蓝桥杯的题目中会超时,因为map查询是对数时间复杂度放在循环中会超时
更改map后通过
#include "stdio.h" #include "string.h" #include "string" #include "iostream" #include "math.h" #include "map" #include "queue" using namespace std; map<char,string> mp; int main() { int a; string test; cin >> a; while(a--) { string b=""; cin>>test; for(int i=0;i<test.length();i++)//遍历,字符串上加上每一位 { switch(test[i]) { case '0':b+="0000";break; case '1':b+="0001";break; case '2':b+="0010";break; case '3':b+="0011";break; case '4':b+="0100";break; case '5':b+="0101";break; case '6':b+="0110";break; case '7':b+="0111";break; case '8':b+="1000";break; case '9':b+="1001";break; case 'A':b+="1010";break; case 'B':b+="1011";break; case 'C':b+="1100";break; case 'D':b+="1101";break; case 'E':b+="1110";break; case 'F':b+="1111";break; default:break; } } int len = b.length(); if(len%3==1) b = "00" + b; else if(len%3==2) b = "0" + b; int flag = 0; for(int i = 0 ;i < b.length(); i = i + 3) { int num = 4*(b[i]-'0')+2*(b[i+1]-'0')+(b[i+2]-'0'); if(num) flag = 1; if(flag) cout<<num; } cout<<endl; } return 0; }