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 public int StrobogrammaticInRange(string low, string high) { 3 int count = 0; 4 long l = Int64.Parse(low), h = Int64.Parse(high); 5 6 for (int n = low.Length; n <= high.Length; n++) 7 { 8 var res = DFS(n, n); 9 10 foreach (var r in res) 11 { 12 var rl = Int64.Parse(r); 13 if (rl >= l && rl <= h) 14 { 15 count++; 16 } 17 } 18 } 19 20 return count; 21 } 22 23 private IList<string> DFS(int n, int m) 24 { 25 if (n == 0) 26 { 27 return new List<string>() {""}; 28 } 29 30 if (n == 1) 31 { 32 return new List<string>() {"0", "1", "8"}; 33 } 34 35 var list = DFS(n - 2, m); 36 var result = new List<string>(); 37 38 foreach (var s in list) 39 { 40 if (n != m) 41 { 42 result.Add("0" + s + "0"); 43 } 44 45 result.Add("1" + s + "1"); 46 result.Add("9" + s + "6"); 47 result.Add("8" + s + "8"); 48 result.Add("6" + s + "9"); 49 } 50 51 return result; 52 } 53 }
时间: 2024-10-07 14:48:39