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;
}
}