Skip to content

Commit 307633e

Browse files
committed
O(n) time and O(n) space
1 parent 092f15b commit 307633e

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
"""
2+
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.
3+
4+
5+
6+
Example 1:
7+
8+
Input: n = 1
9+
Output: 1
10+
Explanation: "1" in binary corresponds to the decimal value 1.
11+
Example 2:
12+
13+
Input: n = 3
14+
Output: 27
15+
Explanation: In binary, 1, 2, and 3 corresponds to "1", "10", and "11".
16+
After concatenating them, we have "11011", which corresponds to the decimal value 27.
17+
Example 3:
18+
19+
Input: n = 12
20+
Output: 505379714
21+
Explanation: The concatenation results in "1101110010111011110001001101010111100".
22+
The decimal value of that is 118505380540.
23+
After modulo 109 + 7, the result is 505379714.
24+
25+
26+
Constraints:
27+
28+
1 <= n <= 105
29+
"""
30+
class Solution:
31+
def concatenatedBinary(self, n: int) -> int:
32+
result = ''
33+
for i in range(1,n+1):
34+
result += "{0:b}".format(i)
35+
return min(int(result,2), int(result,2) % (10**9 + 7))

0 commit comments

Comments
 (0)