diff options
| author | Paulo Custodio <pauloscustodio@gmail.com> | 2021-01-25 23:10:01 +0000 |
|---|---|---|
| committer | Paulo Custodio <pauloscustodio@gmail.com> | 2021-01-26 00:07:19 +0000 |
| commit | e36daeee6e93355383ad3a1c3fc43271f9a357d7 (patch) | |
| tree | 094084c17e6b2ea9df64acbf7b93b18dda8346d3 /challenge-097/paulo-custodio/cpp/ch-2.cpp | |
| parent | 3fa58628535d4041c7cc648c005080ca88f18c18 (diff) | |
| download | perlweeklychallenge-club-e36daeee6e93355383ad3a1c3fc43271f9a357d7.tar.gz perlweeklychallenge-club-e36daeee6e93355383ad3a1c3fc43271f9a357d7.tar.bz2 perlweeklychallenge-club-e36daeee6e93355383ad3a1c3fc43271f9a357d7.zip | |
Add Perl, Basic, C, C++, Forth, Lua and Python solutions to challenge 097
Diffstat (limited to 'challenge-097/paulo-custodio/cpp/ch-2.cpp')
| -rw-r--r-- | challenge-097/paulo-custodio/cpp/ch-2.cpp | 50 |
1 files changed, 50 insertions, 0 deletions
diff --git a/challenge-097/paulo-custodio/cpp/ch-2.cpp b/challenge-097/paulo-custodio/cpp/ch-2.cpp new file mode 100644 index 0000000000..9eff10ac52 --- /dev/null +++ b/challenge-097/paulo-custodio/cpp/ch-2.cpp @@ -0,0 +1,50 @@ +/* +Challenge 097 + +TASK #2 › Binary Substings +Submitted by: Mohammad S Anwar +You are given a binary string $B and an integer $S. + +Write a script to split the binary string $B of size $S and then find the +minimum number of flips required to make it all the same. + +Example 1: +Input: $B = “101100101”, $S = 3 +Output: 1 + +Binary Substrings: + "101": 0 flip + "100": 1 flip to make it "101" + "101": 0 flip +Example 2: +Input $B = “10110111”, $S = 4 +Output: 2 + +Binary Substrings: + "1011": 0 flip + "0111": 2 flips to make it "1011" +*/ + +#include <iostream> +#include <string> + +int str_flips(const char* a, const char* b, int n) { + int flips = 0; + for (int i = 0; i < n; i++) { + if (a[i] != b[i]) + flips++; + } + return flips; +} + +int bit_flips(const std::string& bits, int n) { + int flips = 0; + for (int i = n; i < static_cast<int>(bits.size()); i += n) + flips += str_flips(bits.c_str(), bits.c_str()+i, n); + return flips; +} + +int main(int argc, char* argv[]) { + if (argc == 3) + std::cout << bit_flips(std::string(argv[1]), atoi(argv[2])) << std::endl; +} |
