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.

Example:

Input: low = "50", high = "100"
Output: 3 
Explanation: 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.

思路: 既然是follow up,那么就承接 Strobogrammatic Number II  的代码;利用II的代码,生成size为low 和high的数字,然后判断一下是否在范围内即可,注意用Long来计算,防止爆范围;

class Solution {
    public int strobogrammaticInRange(String low, String high) {
        int lowlen = low.length();
        int highlen = high.length();
        int count = 0;
        long lownum = Long.parseLong(low);
        long highnum = Long.parseLong(high);
        for(long i = lowlen; i <= highlen; i++) {
            List<String> list = helper(i, i);
            for(String str: list) {
                long temp = Long.parseLong(str);
                if(lownum <= temp && temp <= highnum) {
                    count++;
                }
            }
        }
        return count;
    }
    
    private List<String> helper(long curlen, long n) {
        if(curlen == 0) {
            return new ArrayList<String>(Arrays.asList(""));
        }
        if(curlen == 1) {
            return new ArrayList<String>(Arrays.asList("0", "1", "8"));
        }
        //假设当前已经做好了 n - 2的size的数字,只需最后一层;
        List<String> list = helper(curlen - 2, n);
        List<String> res = new ArrayList<String>();
        for(String str: list) {
            // 这个很巧妙,也就是最最外面的一层,不能加0;里面都可以加0;
            if(curlen != n) {
                res.add("0" + str + "0");
            }
            res.add("1" + str + "1");
            res.add("6" + str + "9");
            res.add("9" + str + "6");
            res.add("8" + str + "8");
        }
        return res;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值