[LeetCode] Strobogrammatic Number III

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.

Note:
Because the range might be a large number, the low and high numbers are represented as string.

 

 1 public class Solution {
 2     private int count = 0;
 3     public int strobogrammaticInRange(String low, String high) {
 4         find(low, high, "");
 5         find(low, high, "0");
 6         find(low, high, "1");
 7         find(low, high, "8");
 8         return count;
 9     }
10     private void find(String low, String high, String s){
11         //all possible strobogrammatic numbers that are needed to account for 
12         //must have the length of [low.length(), high.length()]
13         if(s.length() >= low.length() && s.length() <= high.length()){
14             //ignore the numbers that have the same length with low but are 
15             //smaller than low. Similarly, ignore the numbers that have the 
16             //same length with high but are bigger than high
17             if(s.length() == low.length() && s.compareTo(low) < 0 || 
18                 s.length() == high.length() && s.compareTo(high) > 0){
19                 return;
20             }
21             //ignore the cases where s.equals("0") == false && s.charAt(0) == '0'
22             if(!(s.length() > 1 && s.charAt(0) == '0')){
23                 count++;
24             }
25         }
26         //recursion exit condition: if s.length() is already bigger than the 
27         //upper bound length, then there is no need to keep searching, exit!
28         else if(s.length() > high.length()){
29             return;
30         }
31         find(low, high, "0" + s + "0");
32         find(low, high, "1" + s + "1");
33         find(low, high, "6" + s + "9");
34         find(low, high, "8" + s + "8");
35         find(low, high, "9" + s + "6");
36     }
37 }

 

 

Related Problems

Strobogrammatic Number II

posted @ 2019-11-24 02:41  Review->Improve  阅读(256)  评论(0编辑  收藏  举报