LeetCode #248 - Strobogrammatic Number III

本文介绍了一种特殊类型的数字——Astrobogrammatic数,这类数字在旋转180度后仍保持不变。文章探讨了如何编写一个函数来计算在特定范围内存在的Astrobogrammatic数的总数,例如,在输入范围50到100之间,69、88和96是符合条件的三个Astrobogrammatic数。

摘要生成于 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.

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.

class Solution {
public:
    int strobogrammaticInRange(string low, string high) {
        int result=0;
        helper(low,high,"",result);
        helper(low,high,"1",result);
        helper(low,high,"0",result);
        helper(low,high,"8",result);
        return result;
    }
    
    void helper(string& low, string& high, string cur, int& result)
    {
        if(cur.size()>high.size()) return;
        else if(cur.size()>=low.size()&&cur.size()<=high.size())
        {
            if(cur.size()==high.size()&&cur>high) return;
            if(cur.size()==low.size()&&cur<low) return;
            //当第一个字符为0时不能return,比如0也可以变为101,因此我们只需要不对result++,但是要让这种情况继续递归
            if(!(cur.size()>1&&cur[0]=='0')) result++;
        }
        helper(low,high,"1"+cur+"1",result);
        helper(low,high,"0"+cur+"0",result);
        helper(low,high,"6"+cur+"9",result);
        helper(low,high,"9"+cur+"6",result);
        helper(low,high,"8"+cur+"8",result);
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值