Sponsored
Sponsored
This method leverages bit manipulation to efficiently construct the resulting number without physically concatenating binary strings. As each integer from 1 to n is processed, its binary representation is appended using bitwise operations, which helps avoid the overhead of string manipulation.
Time Complexity: O(n), because we process each number from 1 to n.
Space Complexity: O(1), as we use a fixed amount of additional space.
1using System;
2
3public class Solution {
4 public int ConcatenatedBinary(int n) {
5 const int MOD = 1000000007;
6 long result = 0;
7 int bitLength = 0;
8 for (int i = 1; i <= n; i++) {
9 if ((i & (i - 1)) == 0) bitLength++;
10 result = ((result << bitLength) | i) % MOD;
11 }
12 return (int)result;
13 }
14
15 public static void Main() {
16 Solution sol = new Solution();
17 Console.WriteLine(sol.ConcatenatedBinary(12));
18 }
19}
This C# implementation mirrors the logic in other languages, efficiently computing the binary sequence. Modulo operations manage the large possible values, and bit operations allow for smooth sequence construction.
This naive strategy involves directly constructing the final binary string representation step by step. After forming the complete string, it converts it to an integer and performs modulo operation. This approach might be less efficient for large n due to string operations being costly.
Time Complexity: O(n * log n), as string operations for binary conversions dominate computation time.
Space Complexity: O(n * log n), due to the storage of the growing binary string.
In C, string functions manage concatenation, with each conversion translated into a final binary integer checked by modulo for managing size.