Find position of the given number among the numbers made of 4 and 7 in C++

C++Server Side ProgrammingProgramming

In this problem we are given a number N. Our task is to Find position of the given number among the numbers made of 4 and 7. The series consisting of 4 and 7 only is 4, 7, 44, 47, 74, 77, 444….

Let’s take an example to understand the problem,

Input

N = 5

Output

74

Explanation

Series upto 5 terms is 4, 7, 44, 47, 74…

Solution Approach

A simple solution to the problem is based on finding the pattern in the series.

Here, every even position contains 7 in the end.

And every odd position contains 4 in the end.

So, we can find the series by going digit by digit and finding the position based on the current digit.

If the current digit is 4, the position will be updated as position = (position*2) + 1.

If the current digit is 7, the position will be updated as position = (position*2) + 2.

Program to illustrate the working of our solution,

Example

 Live Demo

#include <iostream>
using namespace std;
int findNumPosition(string num){
   int i = 0, position = 0;
   while (num[i] != '\0') {
      position *= 2;
      if(num[i] == '4')
         position += 1;
      else
         position += 2;
      i++;
   }
   return position;
}
int main() {
   string num = "74774";
   cout<<"The position of the number in the series is "<<findNumPosition(num);
   return 0;
}

Output

The position of the number in the series is 53
raja
Published on 16-Mar-2021 05:14:00
Advertisements