- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions

# Program to find concatenation of consecutive binary numbers in Python

Suppose we have a number n, we have to find the decimal value of the binary string by concatenating the binary representations of 1 to n one by one in order, if the answer is too large then return answer modulo 10^9 + 7.

So, if the input is like n = 4, then the output will be 220 because, by concatenating binary representation from 1 to 4 will be "1" + "10" + "11" + "100" = 110111000, this is binary representation of 220.

To solve this, we will follow these steps −

- ans := 1
- m := 10^9+7
- for i in range 2 to n, do
- ans := shift ans (bit length of i) number of times
- ans := (ans+i) mod m

- return ans

## Example

Let us see the following implementation to get better understanding −

def solve(n): ans = 1 m = (10**9+7) for i in range(2,n+1): ans = ans<<i.bit_length() ans = (ans+i) % m return ans n = 4 print(solve(n))

## Input

4

## Output

220

- Related Articles
- Program to find numbers with same consecutive differences in Python
- Program to find length of longest consecutive path of a binary tree in python
- Program to find longest consecutive run of 1s in binary form of n in Python
- Python Program to Count number of binary strings without consecutive 1’
- Program to find length of longest consecutive sequence in Python
- Python program for sum of consecutive numbers with overlapping in lists
- Program to find sum of all numbers formed by path of a binary tree in python
- Python program to find the length of the largest consecutive 1's in Binary Representation of a given string.
- Program to find longest consecutive run of 1 in binary form of a number in C++
- Program to partitioning into minimum number of Deci- Binary numbers in Python
- Find missing element in a sorted array of consecutive numbers in Python
- Program to find length of substring with consecutive common characters in Python
- Program to find minimum number of subsequence whose concatenation is same as target in python
- 1 to n bit numbers with no consecutive 1s in binary representation?
- Python program to check if there are K consecutive 1’s in a binary number?

Advertisements