A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).
Write a function to count the total strobogrammatic numbers that exist in the range of low <= num <= high.
Example:
Input: low = "50", high = "100" Output: 3 Explanation: 69, 88, and 96 are three strobogrammatic numbers.
Note:
Because the range might be a large number, the low and high numbers are represented as string.
思路: 既然是follow up,那么就承接 Strobogrammatic Number II 的代码;利用II的代码,生成size为low 和high的数字,然后判断一下是否在范围内即可,注意用Long来计算,防止爆范围;
class Solution {
public int strobogrammaticInRange(String low, String high) {
int lowlen = low.length();
int highlen = high.length();
int count = 0;
long lownum = Long.parseLong(low);
long highnum = Long.parseLong(high);
for(long i = lowlen; i <= highlen; i++) {
List<String> list = helper(i, i);
for(String str: list) {
long temp = Long.parseLong(str);
if(lownum <= temp && temp <= highnum) {
count++;
}
}
}
return count;
}
private List<String> helper(long curlen, long n) {
if(curlen == 0) {
return new ArrayList<String>(Arrays.asList(""));
}
if(curlen == 1) {
return new ArrayList<String>(Arrays.asList("0", "1", "8"));
}
//假设当前已经做好了 n - 2的size的数字,只需最后一层;
List<String> list = helper(curlen - 2, n);
List<String> res = new ArrayList<String>();
for(String str: list) {
// 这个很巧妙,也就是最最外面的一层,不能加0;里面都可以加0;
if(curlen != n) {
res.add("0" + str + "0");
}
res.add("1" + str + "1");
res.add("6" + str + "9");
res.add("9" + str + "6");
res.add("8" + str + "8");
}
return res;
}
}