# Strobogrammatic Number III in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

Best Seller

66 Lectures 5.5 hours

Suppose we want to define a function to count the total strobogrammatic numbers that exist in the range of (low and high). As we know that a strobogrammatic number is a number that looks the same when rotated 180 degrees.

So, if the input is like low = "50", high = "100", then the output will be 3 as there are three results, 69, 88, and 96.

To solve this, we will follow these steps −

• Define a function findStrobogrammatic(), this will take n,

• Define an array ret

• if n & 1 is non-zero, then −

• insert "0" at the end of ret

• insert "1" at the end of ret

• insert "8" at the end of ret

• Otherwise

• insert blank string at the end of ret

• for n > 1, update n := n - 2, do −

• Define an array temp

• for initialize i := 0, when i < size of ret, update (increase i by 1), do −

• s := ret[i]

• if n > 3, then −

• insert "0" + s + "0" at the end of temp

• insert "1" + s + "1" at the end of temp

• insert "8" + s + "8" at the end of temp

• insert "6" + s + "9" at the end of temp

• insert "9" + s + "6" at the end of temp

• ret := temp

• return ret

• From the main method, do the following −

• ret := 0

• Define an array v

• for initialize i := size of low, when i <= size of high, update (increase i by 1), do −

• v := findStrobogrammatic(i)

• for initialize j := 0, when j < size of v, update (increase j by 1), do −

• ret := ret + (1 when length of v[j] > length of low AND length of high > length of v[j])

• return ret

## Example

Let us see the following implementation to get better understanding −

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<string> findStrobogrammatic(int n) {
vector<string> ret;
if (n & 1) {
ret.push_back("0");
ret.push_back("1");
ret.push_back("8");
}
else {
ret.push_back("");
}
for (; n > 1; n -= 2) {
vector<string> temp;
for (int i = 0; i < ret.size(); i++) {
string s = ret[i];
if (n > 3) {
temp.push_back("0" + s + "0");
}
temp.push_back("1" + s + "1");
temp.push_back("8" + s + "8");
temp.push_back("6" + s + "9");
temp.push_back("9" + s + "6");
}
ret = temp;
}
return ret;
}
bool compare(string a, string b){
return a.size() == b.size() ? a >= b : a.size() > b.size();
}
int strobogrammaticInRange(string low, string high) {
int ret = 0;
vector<string> v;
for (int i = low.size(); i <= high.size(); i++) {
v = findStrobogrammatic(i);
for (int j = 0; j < v.size(); j++) {
ret += compare(v[j], low) && compare(high, v[j]);
}
}
return ret;
}
};
main(){
Solution ob;
cout <<(ob.strobogrammaticInRange("50", "100"));
}

## Input

"50","100"

## Output

3
Updated on 21-Jul-2020 07:50:23