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.
1const concatenatedBinary = function(n) {
2 const MOD = 1000000007;
3 let result = 0;
4 let bitLength = 0;
5 for (let i = 1; i <= n; i++) {
6 if ((i & (i - 1)) === 0) bitLength++;
7 result = ((result << bitLength) | i) % MOD;
8 }
9 return result;
10};
11
12console.log(concatenatedBinary(12));
The JavaScript solution follows the approach of efficiently constructing the binary sequence without excessive memory or time use. It optimally manages bit operations to append numbers to the result under modulo constraints.
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.
Java uses a StringBuilder to gather binary string components, convert them to an integer through BigInteger, then applies modulo to get the final result.