[LeetCode] Concatenation of Consecutive Binary Numbers

1680. Concatenation of Consecutive Binary Numbers

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.

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
int mod = 1e9 + 7;
public:
int concatenatedBinary(int n) {
long res = 0, shift = 0;
for(int i = 1; i <= n; i++) {
if((i & (i-1)) == 0) shift++;
res = ((res<<shift) % mod + i) % mod;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/13/PS/LeetCode/concatenation-of-consecutive-binary-numbers/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.