码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 248: Strobogrammatic Number III

时间:2017-12-18 14:19:10      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:return   repr   int   and   span   ota   style   new   pos   

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 }

 

Leetcode 248: Strobogrammatic Number III

标签:return   repr   int   and   span   ota   style   new   pos   

原文地址:http://www.cnblogs.com/liangmou/p/8057050.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!