Concatenation of Consecutive Binary Numbers

medium math bit modular

Problem

Given n, return the decimal value (mod 1e9+7) of the string formed by concatenating binary representations of 1..n in order.

Inputn = 3
Output27
"1" "10" "11" → "11011" = 27.

def concatenated_binary(n):
    MOD = 10**9 + 7
    ans = 0
    for i in range(1, n + 1):
        ans = ((ans << i.bit_length()) + i) % MOD
    return ans
function concatenatedBinary(n) {
  const MOD = 1000000007n;
  let ans = 0n;
  for (let i = 1; i <= n; i++) {
    const bits = BigInt(32 - Math.clz32(i));
    ans = ((ans << bits) + BigInt(i)) % MOD;
  }
  return Number(ans);
}
class Solution {
    public int concatenatedBinary(int n) {
        long MOD = 1_000_000_007L, ans = 0;
        for (int i = 1; i <= n; i++) {
            int bits = 32 - Integer.numberOfLeadingZeros(i);
            ans = (((ans << bits) % MOD) + i) % MOD;
        }
        return (int) ans;
    }
}
int concatenatedBinary(int n) {
    const long MOD = 1000000007;
    long ans = 0;
    for (int i = 1; i <= n; i++) {
        int bits = 32 - __builtin_clz(i);
        ans = (((ans << bits) % MOD) + i) % MOD;
    }
    return (int) ans;
}
Time: O(n) Space: O(1)