Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created February 28, 2026 18:19
Show Gist options
  • Select an option

  • Save tatsuyax25/f4437429c95b6720ee41777cf7d84d2c to your computer and use it in GitHub Desktop.

Select an option

Save tatsuyax25/f4437429c95b6720ee41777cf7d84d2c to your computer and use it in GitHub Desktop.
Given an integer n, return the decimal value of the binary string formed by concatenating the binary representations of 1 to n in order, modulo 109 + 7.
/**
* @param {number} n
* @return {number}
*/
var concatenatedBinary = function(n) {
const MOD = 1_000_000_007;
let ans = 0;
let bitLength = 0;
let pow2 = 1; // this will always store 2^bitLength % MOD
for (let i = 1; i <= n; i++) {
// If i is a power of two, bitLength increases
if ((i & (i - 1)) === 0) {
bitLength++;
pow2 = (pow2 * 2) % MOD; // update 2^bitLength safely
}
// Shift left by multiplying with pow2 (instead of ans << bitLength)
ans = (ans * pow2 + i) % MOD;
}
return ans;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment