leetcode 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.

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.

思路其实挺简单的,递归字符串长度直至大于等于low,小于等于high,到了这里之后需要考虑几种边界值的情况:

1、长度等于low,但值小于low

2、长度等于high,值大于high

3、首尾为0的情况,需要过滤掉

private int num=0;
public int strobogrammaticInRange(String low, String high) {
    getSum(low,high,"");
    getSum(low,high,"8");
    getSum(low,high,"1");
    getSum(low,high,"0");
    return num;
}
public void getSum(String low,String high,String str){
    if(str.length()>=low.length()&&str.length()<=high.length()){
        if(str.length()==low.length()&&str.compareTo(low)<0) return;
        if(str.length()==high.length()&&str.compareTo(high)>0) return;
        if(str.length()==1||(str.length()>1&&str.charAt(0)!='0'))
            num+=1;
    }
    if(str.length()+2>high.length()) return;
    getSum(low,high,"1"+str+"1");
    getSum(low,high,"8"+str+"8");
    getSum(low,high,"0"+str+"0");
    getSum(low,high,"6"+str+"9");
    getSum(low,high,"9"+str+"6");

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值