We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
question is quite straightforward, but lots of things to consider, and very long code
vector<bitset<4>>HexToBinary(stringx){vector<bitset<4>>result;for(inti=0;i<x.size();i++){intk;if(x[i]<=57){k=x[i]-48;}else{k=x[i]-55;}bitset<4>temp(k);result.push_back(temp);}returnresult;}stringBinaryToHex(vector<bitset<4>>x){stringresult;for(inti=0;i<x.size();i++){intk=x[i].to_ulong();if(k<10){result.push_back(static_cast<char>(k+48));}else{result.push_back(static_cast<char>(k+55));}}intindex=0;while(index<result.size()-1){if(result[index]!='0'){break;}index++;}result.erase(result.begin(),result.begin()+index);returnresult;}voidaOrB(intk,stringa,stringb,stringc){vector<bitset<4>>binaryA=HexToBinary(a);vector<bitset<4>>binaryB=HexToBinary(b);vector<bitset<4>>binaryC=HexToBinary(c);intchangesRemaining=k;//make necessary changes to A and Bintd1=binaryA.size()-binaryC.size();intd2=binaryB.size()-binaryC.size();for(inti=0;i<d1;i++){changesRemaining=changesRemaining-binaryA[i].count();}for(inti=0;i<d2;i++){changesRemaining=changesRemaining-binaryB[i].count();}binaryA.erase(binaryA.begin(),binaryA.begin()+d1);binaryB.erase(binaryB.begin(),binaryB.begin()+d2);d1=binaryA.size()-binaryC.size();d2=binaryB.size()-binaryC.size();binaryA.insert(binaryA.begin(),abs(d1),bitset<4>());binaryB.insert(binaryB.begin(),abs(d2),bitset<4>());for(inti=0;i<binaryC.size();i++){for(intj=3;j>=0;j--){if(binaryC[i][j]==0){changesRemaining=changesRemaining-binaryA[i][j]-binaryB[i][j];binaryA[i][j]=0;binaryB[i][j]=0;}if(binaryC[i][j]==1and(binaryA[i][j]|binaryB[i][j])==0){binaryB[i][j]=1;changesRemaining--;}}}if(changesRemaining<0){cout<<-1<<"\n";return;}//optimize A and B, try to make A the smallest possiblefor(inti=0;i<binaryC.size();i++){for(intj=3;j>=0;j--){if(changesRemaining==0){cout<<BinaryToHex(binaryA)<<"\n"<<BinaryToHex(binaryB)<<"\n";return;}if(binaryC[i][j]==1){if((binaryA[i][j]&binaryB[i][j])==1){binaryA[i][j]=0;changesRemaining--;}elseif(binaryA[i][j]==1andbinaryB[i][j]==0andchangesRemaining>=2){binaryA[i][j]=0;binaryB[i][j]=1;changesRemaining=changesRemaining-2;}}}}cout<<BinaryToHex(binaryA)<<"\n"<<BinaryToHex(binaryB)<<"\n";}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
A or B
You are viewing a single comment's thread. Return to all comments →
question is quite straightforward, but lots of things to consider, and very long code