An integer is called fortunate if its canonical binary representation contains the contiguous substring "101" at least once. The canonical representation has no leading zeros, and zero is represented as "0".
Given two integers left and right, return the number of fortunate integers in the inclusive range [left, right]. Each integer is counted once, even if "101" appears in it several times or the occurrences overlap (for example, 21 is 10101 in binary and counts once).
Function Signature
def count_fortunate_numbers(left: int, right: int) -> int:
...
Rules
-
Both ends of the range are included.
-
The test uses the canonical binary form of each integer, with no leading zeros. Zero is
"0"
and is not fortunate.
-
The substring must be contiguous:
9
is
1001
, which has the digits 1, 0 and 1 but not next to each other, so it is not fortunate.
Constraints
-
0 <= left <= right <= 10^12
-
The inputs and the returned count fit in a 64-bit signed integer.
Examples
Input: left = 4, right = 6
Output: 1
4 is 100, 5 is 101 and 6 is 110. Only 5 contains "101", so the answer is 1.
Input: left = 16, right = 23
Output: 4
16 = 10000, 17 = 10001, 18 = 10010 and 19 = 10011 do not contain "101". 20 = 10100, 21 = 10101, 22 = 10110 and 23 = 10111 all do, and 21 counts once even though its two occurrences overlap.
Input: left = 0, right = 15
Output: 4
The fortunate values from 0 to 15 are 5 = 101, 10 = 1010, 11 = 1011 and 13 = 1101. Every other value in the range, including 9 = 1001, lacks a contiguous "101".