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.
1class Solution {
2 public int concatenatedBinary(int n) {
3 int MOD = 1000000007;
4 long result = 0;
5 int bitLength = 0;
6 for (int i = 1; i <= n; i++) {
7 if ((i & (i - 1)) == 0) bitLength++;
8 result = ((result << bitLength) | i) % MOD;
9 }
10 return (int) result;
11 }
12}
The Java solution follows a similar approach to the Python one. We calculate the number of bits for each new power of 2 and perform a left shift and binary OR operation to append the number, ensuring the result stays within limits using modulo operations.
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.