From a48dd4765e02bdace3e8298fb6926e4b47a68688 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Tue, 12 Dec 2023 14:46:33 +0100 Subject: [PATCH] =?UTF-8?q?problems(cpp):=20add=20=E2=80=9C1680.=20Concate?= =?UTF-8?q?nation=20of=20Consecutive=20Binary=20Numbers=E2=80=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- ...tenation-of-consecutive-binary-numbers.cpp | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 cpp/concatenation-of-consecutive-binary-numbers.cpp diff --git a/cpp/concatenation-of-consecutive-binary-numbers.cpp b/cpp/concatenation-of-consecutive-binary-numbers.cpp new file mode 100644 index 0000000..999a72d --- /dev/null +++ b/cpp/concatenation-of-consecutive-binary-numbers.cpp @@ -0,0 +1,34 @@ +#include + +class Solution { + static const int MOD = 1000000007; + +public: + int concatenatedBinary(int n) + { + long joined_number = 0; + + int padding = 1; + for (int i = 1; i <= n; i++) { + joined_number = ((joined_number << padding) + i) % MOD; + + if ((i & (i + 1)) == 0) { + padding++; + } + } + + return joined_number; + } +}; + +int main() +{ + Solution s; + + assert(s.concatenatedBinary(1) == 1); + assert(s.concatenatedBinary(2) == 6); + assert(s.concatenatedBinary(3) == 27); + assert(s.concatenatedBinary(12) == 505379714); + + return 0; +}