leetcode Strobogrammatic Number III

来源:互联网 发布:数据库的安全防护措施 编辑:程序博客网 时间:2024/06/10 05:23

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");}

0 0
原创粉丝点击