/**
* Problem: LeetCode 1680 - Concatenation of Consecutive Binary Numbers
* Difficulty: Medium
* Language: Java
* Author: CodeByTushu
*/
class Solution {
public int concatenatedBinary(int n) {
long ans = 0;
int bitLength = 0;
final long MOD = 1_000_000_007L;
for (int i = 1; i <= n; i++) {
// When i is a power of 2, its binary representation requires one more bit
if ((i & (i - 1)) == 0) {
bitLength++;
}
ans = ((ans << bitLength) | i) % MOD;
}
return (int) ans;
}
}
"""
Problem: LeetCode 1680 - Concatenation of Consecutive Binary Numbers
Difficulty: Medium
Language: Python
Author: CodeByTushu
"""
class Solution:
def concatenatedBinary(self, n: int) -> int:
ans = 0
bit_length = 0
MOD = 1_000_000_007
for i in range(1, n + 1):
if (i & (i - 1)) == 0:
bit_length += 1
ans = ((ans << bit_length) | i) % MOD
return ans
/**
* Problem: LeetCode 1680 - Concatenation of Consecutive Binary Numbers
* Difficulty: Medium
* Language: C++
* Author: CodeByTushu
*/
#include <iostream>
using namespace std;
class Solution {
public:
int concatenatedBinary(int n) {
long long ans = 0;
int bitLength = 0;
const long long MOD = 1'000'000'007LL;
for (int i = 1; i <= n; i++) {
// When i is a power of 2, its binary representation increases by 1 bit
if ((i & (i - 1)) == 0) {
bitLength++;
}
ans = ((ans << bitLength) | i) % MOD;
}
return static_cast<int>(ans);
}
};
/**
* Problem: LeetCode 1680 - Concatenation of Consecutive Binary Numbers
* Difficulty: Medium
* Language: JavaScript
* Author: CodeByTushu
*/
/**
* @param {number} n
* @return {number}
*/
var concatenatedBinary = function(n) {
let ans = 0n;
let bitLength = 0n;
const MOD = 1000000007n;
for (let i = 1n; i <= BigInt(n); i++) {
// When i is a power of 2, its binary representation requires one more bit
if ((i & (i - 1n)) === 0n) {
bitLength++;
}
ans = ((ans << bitLength) | i) % MOD;
}
return Number(ans);
};