Skip to content

Commit f79e33b

Browse files
committed
EPI: swap bits
1 parent 0a68737 commit f79e33b

File tree

2 files changed

+40
-3
lines changed

2 files changed

+40
-3
lines changed
Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,41 @@
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+
233
long 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

741
int 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

elements-of-programming-interviews/problem_mapping.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ problem_mapping = {
3030
},
3131
"4.02 Swap bits": {
3232
"C++: swap_bits.cc": {
33-
"passed": 0,
33+
"passed": 10001,
3434
"total": 10001
3535
},
3636
"Java: SwapBits.java": {

0 commit comments

Comments
 (0)