Input:
n = 1
Output:
1
Explanation: "1" in binary corresponds to the decimal value 1.
Example 2:
1
2
3
4
5
6
Input:
n = 3
Output:
27
Explanation: In binary, 1, 2, and 3 corresponds to "1", "10", and "11".
After concatenating them, we have "11011", which corresponds to the decimal value 27.
Example 3:
1
2
3
4
5
6
7
Input:
n = 12
Output:
505379714
**Explanation**: The concatenation results in "1101110010111011110001001101010111100".
The decimal value of that is 118505380540.
After modulo 10^9 + 7, the result is 505379714.
To efficiently concatenate the binary representations of numbers from 1 to n, we use bitwise operations. For each number, we shift the current result left by the number of bits in the new number and add the new number, taking modulo at each step to avoid overflow.
classSolution {
publicintconcatenatedBinary(int n) {
int mod = 1000000007;
long ans = 0;
for (int i = 1; i <= n; i++) {
int bits = Integer.toBinaryString(i).length();
ans = ((ans << bits) | i) % mod;
}
return (int)ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
public:int concatenatedBinary(int n) {
int mod =1e9+7;
longlong ans =0;
for (int i =1; i <= n; ++i) {
int bits =32- __builtin_clz(i);
ans = ((ans << bits) | i) % mod;
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
funcconcatenatedBinary(nint) int {
mod:= int(1e9+7)
ans:=0fori:=1; i<=n; i++ {
bits:=0forx:=i; x > 0; x>>=1 {
bits++ }
ans = ((ans<<bits) | i) %mod }
returnans}
1
2
3
4
5
6
7
8
classSolution:
defconcatenatedBinary(self, n: int) -> int:
mod =10**9+7 ans =0for i in range(1, n+1):
bits = i.bit_length()
ans = ((ans << bits) | i) % mod
return ans
1
2
3
4
5
6
7
8
9
10
11
impl Solution {
pubfnconcatenated_binary(n: i32) -> i32 {
let modv =1_000_000_007;
letmut ans: i64=0;
for i in1..=n {
let bits =32- (i.leading_zeros() asi32);
ans = ((ans << bits) | i asi64) % modv;
}
ans asi32 }
}