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.
For example,
Given low = "50", high = "100", return 3. Because 69, 88, and 96 are three strobogrammatic numbers.
Given low = "50", high = "100", return 3. Because 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.
Because the range might be a large number, the low and high numbers are represented as string.
public int strobogrammaticInRange(String low, String high) {
if (low.length() > high.length() || (low.length() == high.length() && low.compareTo(high) > 0)) return 0;
LinkedList<String> pre = new LinkedList<>();
pre.add("");
LinkedList<String> cur = new LinkedList<>();
cur.add("1");
cur.add("8");
cur.add("0");
int sl = low.length();
int hl = high.length();
int n = 1;
int res = 0;
while (true) {
if (n >= sl && n <= hl) {
for (String s : cur) {
if (s.charAt(0) == '0' && s.length() != 1) {
continue;
}
if (n == sl && s.compareTo(low) < 0) {
continue;
}
if (n == hl && s.compareTo(high) > 0) {
continue;
}
res++;
}
}
if (n == hl) {
break;
}
LinkedList<String> next = getNextStro(pre);
pre = cur;
cur = next;
n++;
}
return res;
}
private LinkedList<String> getNextStro(LinkedList<String> pre) {
int count = pre.size();
while (count-- > 0) {
String s = pre.poll();
pre.addLast("0" + s + "0");
pre.addLast("1" + s + "1");
pre.addLast("8" + s + "8");
pre.addLast("6" + s + "9");
pre.addLast("9" + s + "6");
}
return pre;
}
}
没有评论:
发表评论