diff options
| author | Paulo Custodio <pauloscustodio@gmail.com> | 2021-07-05 22:57:40 +0100 |
|---|---|---|
| committer | Paulo Custodio <pauloscustodio@gmail.com> | 2021-07-05 22:57:40 +0100 |
| commit | 95db0bb6b8cd9762c26d8392cda04b3553b38bb4 (patch) | |
| tree | bc5af7a96d8d474e7259d1f235ee64fb9516dbb3 /challenge-120/paulo-custodio/cpp/ch-1.cpp | |
| parent | 39253b822e4bfe790553c560fd7c377f92f6246c (diff) | |
| download | perlweeklychallenge-club-95db0bb6b8cd9762c26d8392cda04b3553b38bb4.tar.gz perlweeklychallenge-club-95db0bb6b8cd9762c26d8392cda04b3553b38bb4.tar.bz2 perlweeklychallenge-club-95db0bb6b8cd9762c26d8392cda04b3553b38bb4.zip | |
Add solutions to challenge 120
Diffstat (limited to 'challenge-120/paulo-custodio/cpp/ch-1.cpp')
| -rw-r--r-- | challenge-120/paulo-custodio/cpp/ch-1.cpp | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/challenge-120/paulo-custodio/cpp/ch-1.cpp b/challenge-120/paulo-custodio/cpp/ch-1.cpp new file mode 100644 index 0000000000..7d25a239ec --- /dev/null +++ b/challenge-120/paulo-custodio/cpp/ch-1.cpp @@ -0,0 +1,46 @@ +/* +Challenge 120 + +TASK #1 - Swap Odd/Even bits +Submitted by: Mohammad S Anwar +You are given a positive integer $N less than or equal to 255. + +Write a script to swap the odd positioned bit with even positioned bit and +print the decimal equivalent of the new binary representation. + +Example +Input: $N = 101 +Output: 154 + +Binary representation of the given number is 01 10 01 01. +The new binary representation after the odd/even swap is 10 01 10 10. +The decimal equivalent of 10011010 is 154. + +Input: $N = 18 +Output: 33 + +Binary representation of the given number is 00 01 00 10. +The new binary representation after the odd/even swap is 00 10 00 01. +The decimal equivalent of 100001 is 33. +*/ + +#include <iostream> +using namespace std; + +int swap_bits(int n) { + int out = 0; + int shift = 0; + while (n > 0) { + if ((n & 1) != 0) { out |= 2 << shift; } + if ((n & 2) != 0) { out |= 1 << shift; } + n >>= 2; + shift += 2; + } + return out; +} + +int main(int argc, char* argv[]) { + int n = 0; + if (argc == 2) n = atoi(argv[1]); + cout << swap_bits(n) << endl; +} |
