5 Ways To Convert Python Integers into Binary Strings
Explained with an algorithm interview question
Python is easy to learn but hard to master.
Sometimes, even if you are a senior Python developer, there are still some tricks you don’t know.
Last week, a simple algorithm interview question on LeetCode made me stuck for a while:
Given a positive integer
n
, there exists a 0-indexed array calledpowers
, composed of the minimum number of powers of2
that sum ton
. The array is sorted in non-decreasing order, and there is only one way to form the array.You are also given a 0-indexed 2D integer array
queries
, wherequeries[i] = [lefti, righti]
. Eachqueries[i]
represents a query where you have to find the product of allpowers[j]
withlefti <= j <= righti
.Return an array
answers
, equal in length toqueries
, whereanswers[i]
is the answer to theith
query. Since the answer to theith
query may be too large, eachanswers[i]
should be returned modulo10**9 + 7
.
Example 1:
Input: n = 15, queries = [[0,1],[2,2],[0,3]]
Output: [2,4,64]
Explanation:
For n = 15, powers = [1,2,4,8]. It can be shown that powers cannot be a smaller size.
Answer to 1st query: powers[0] * powers[1] = 1 * 2 = 2.
Answer to 2nd query…