Strobogrammatic Number II in C++


Suppose we have a length n. We have to find all strobogrammatic numbers that are of length n.

As we know that a strobogrammatic number is a number that looks the same when rotated 180 degrees.

So, if the input is like n = 2, then the output will be ["11","69","88","96"]

To solve this, we will follow these steps −

  • Define an array ret

  • if n is odd, 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" concatenate s concatenate "0" at the end of temp

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

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

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

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

    • ret := temp

  • return ret

Example 

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto< v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
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;
   }
};
main(){
   Solution ob;
   print_vector(ob.findStrobogrammatic(3));
}

Input

3

Output

[101, 808, 609, 906, 111, 818, 619, 916, 181, 888, 689, 986, ]

Updated on: 18-Nov-2020

370 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements