aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMohammad S Anwar <Mohammad.Anwar@yahoo.com>2020-09-22 15:41:58 +0100
committerGitHub <noreply@github.com>2020-09-22 15:41:58 +0100
commit73ed7236a4f13f4f57460d6bcfc0dfb2d4c92fc8 (patch)
tree2330e8678d34eccbf9c4b402c058e69512cba191
parentf7ec822a30b2abe381fbd33d68e2ab3cae6c35e8 (diff)
parentd55984d5e2507ead06af6924087bb15338094171 (diff)
downloadperlweeklychallenge-club-73ed7236a4f13f4f57460d6bcfc0dfb2d4c92fc8.tar.gz
perlweeklychallenge-club-73ed7236a4f13f4f57460d6bcfc0dfb2d4c92fc8.tar.bz2
perlweeklychallenge-club-73ed7236a4f13f4f57460d6bcfc0dfb2d4c92fc8.zip
Merge pull request #2348 from ash/master
ash: 079-1 in C++
-rw-r--r--challenge-079/ash/cpp/ch-1.cpp43
1 files changed, 43 insertions, 0 deletions
diff --git a/challenge-079/ash/cpp/ch-1.cpp b/challenge-079/ash/cpp/ch-1.cpp
new file mode 100644
index 0000000000..27596b8967
--- /dev/null
+++ b/challenge-079/ash/cpp/ch-1.cpp
@@ -0,0 +1,43 @@
+/*
+ Task 1 from
+ https://perlweeklychallenge.org/blog/perl-weekly-challenge-079/
+*/
+
+#include <iostream>
+#include <sstream>
+
+using namespace std;
+
+int main(int argc, char** argv) {
+ if (argc != 2) {
+ cerr << "Usage: ./a.out 42" << endl;
+ return 1;
+ }
+
+ stringstream input(argv[1]);
+
+ int n;
+ input >> n;
+
+ int total_bits = 0;
+ int scale = 1;
+ n++;
+ while (scale <= n) {
+ int scale2 = scale << 1;
+
+ int fill_full = n / scale2;
+ int fill_frac = n % scale2;
+
+ int bits_full = fill_full * scale;
+ int bits_frac = 0;
+ if (fill_frac > scale) {
+ bits_frac = fill_frac - scale;
+ }
+
+ total_bits += bits_full + bits_frac;
+
+ scale = scale2;
+ }
+
+ cout << "There are " << total_bits << " set bits in the sequence from 1 to " << n << endl;
+}