题目描述:
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);
}
};