Leetcode 248: Strobogrammatic Number III

本文介绍了一个倒转数计算器,该计算器能找出指定范围内的所有倒转数,并计算总数。倒转数是指当数字旋转180度后看起来不变的数字。例如69、88、96等。文章提供了一段C#代码实现,通过递归方式生成倒转数并进行判断。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 }

 

转载于:https://www.cnblogs.com/liangmou/p/8057050.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值