Created
February 28, 2026 18:19
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * @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