11#include " test_framework/generic_test.h"
2+
3+ void printBin (unsigned long long val, size_t len, const std::string& suffix) {
4+ std::string binval;
5+ for (size_t i = 0 ; i < len; i++) {
6+ binval.append (val & 1 ? " 1" : " 0" );
7+ val >>= 1 ;
8+ }
9+ reverse (binval.begin (), binval.end ());
10+ printf (" %s (%s)\n " , binval.c_str (), suffix.c_str ());
11+ }
12+
13+ long long SwapBitsBruteForce (long long x, int i, int j) {
14+ // Not clever approach:
15+ // 1) Isolate the bit values:
16+ long long ival = x & (1LL << i);
17+ long long jval = x & (1LL << j);
18+
19+ // 2) Clear them in the original string
20+ x &= ~(1LL << i);
21+ x &= ~(1LL << j);
22+
23+ // 3) Now use the isolated values to set them in the swapped places
24+ if (ival) {
25+ x |= (1LL << j);
26+ }
27+ if (jval) {
28+ x |= (1LL << i);
29+ }
30+ return x;
31+ }
32+
233long long SwapBits (long long x, int i, int j) {
3- // TODO - you fill in here.
4- return 0 ;
34+ if (((x >> i) & 1 ) != ((x >> j) & 1 )) {
35+ long long mask = (1LL << i) | (1LL << j);
36+ return x ^ mask;
37+ }
38+ return x;
539}
640
741int main (int argc, char * argv[]) {
@@ -10,3 +44,6 @@ int main(int argc, char* argv[]) {
1044 return GenericTestMain (args, " swap_bits.cc" , " swap_bits.tsv" , &SwapBits,
1145 DefaultComparator{}, param_names);
1246}
47+
48+ // 0000000000000000000100010010101011010110100101010001100010101001
49+ // 00000000000000000001000x0010101011010110100101010001100010101001
0 commit comments