Computer >> Computer tutorials >  >> Programming >> C++

K’th Boom Number in C++


In this tutorial, we are going to write a program that finds the k-th boom number.

The number that contains only 2 and 3 are called boom number.

Let's see the steps to solve the above problem.

  • Initialise the value of k.
  • Initialise a queue of strings.
  • Push the empty string to the queue.
  • Initialise a counter variable to 0.
  • Write a loop that iterates till counter is less than or equal to the given k.
    • Get the front of the queue.
    • Pop the element from the queue.
    • Store the front of the queue in a variable.
    • Push the number after appending 2 to the front.
    • Increment the counter and check whether k is equal to counter or not.
    • If the counter is equal to k, then print the value and break.
    • Push the number after appending 3 to the front.
    • Increment the counter and check whether k is equal to counter or not.
    • Increment the counter and check whether k is equal to counter or not.

Example

Let's see the code.

#include<bits/stdc++.h>
using namespace std;
void findKthBoomNumber(long long k) {
   queue<string> queue;
   queue.push("");
   long long count = 0;
   while (count <= k) {
      string numberOne = queue.front();
      queue.pop();
      string numberTwo = numberOne;
      queue.push(numberOne.append("2"));
      count++;
      if (count == k) {
         cout << numberOne << endl;
         break;
      }
      queue.push(numberTwo.append("3"));
      count++;
      if (count == k) {
         cout << numberTwo << endl;
         break;
      }
   }
}
int main() {
   long long k = 45;
   findKthBoomNumber(k);
   return 0;
}

Output

If you run the above code, then you will get the following result.

23332

Conclusion

If you have any queries in the tutorial, mention them in the comment section.