Given two strings low and high that represent two integers low and high where low <= high, return the number of strobogrammatic numbers in the range[low, high].
A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).
Example 1:
Input: low = "50", high = "100"
Output: 3
Example 2:
Input: low = "0", high = "0"
Output: 1
Constraints:
1 <= low.length, high.length <= 15
low and high consist of only digits.
low <= high
low and high do not contain any leading zeros except for zero itself.
Solutions
Solution 1: Recursion
If the length is \(1\), then the strobogrammatic numbers are only \(0, 1, 8\); if the length is \(2\), then the strobogrammatic numbers are only \(11, 69, 88, 96\).
We design a recursive function \(dfs(u)\), which returns the strobogrammatic numbers of length \(u\).
If \(u\) is \(0\), return a list containing an empty string, i.e., [""]; if \(u\) is \(1\), return the list ["0", "1", "8"].
If \(u\) is greater than \(1\), we traverse all the strobogrammatic numbers of length \(u - 2\). For each strobogrammatic number \(v\), we add \(1, 8, 6, 9\) to both sides of it, and we can get the strobogrammatic numbers of length \(u\).
Note that if \(u \neq n\), we can also add \(0\) to both sides of the strobogrammatic number.
Let the lengths of \(low\) and \(high\) be \(a\) and \(b\) respectively.
Next, we traverse all lengths in the range \([a,..b]\). For each length \(n\), we get all strobogrammatic numbers \(dfs(n)\), and then check whether they are in the range \([low, high]\). If they are, we increment the answer.
The time complexity is \(O(2^{n+2} \times \log n)\).