C++ code to check phone number can be formed from numeric string

C++Server Side ProgrammingProgramming

Suppose we have a string S with n digits. A number with exactly 11 digits is a telephone number if it starts with '8'. In one operation, we can remove one digit from S. We have to check whether we can make the string a valid phone number or not.

So, if the input is like S = "5818005553985", then the output will be True, because we can make the string "8005553985" with 11 characters and first digit is 8.

Steps

To solve this, we will follow these steps −

m := size of S
insert '8' at the end of S
if if location of 8 <= (m - 11), then:
   return true
return false

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
bool solve(string S){
   int m = S.size();
   S.push_back('8');
   if ((int(S.find('8')) <= (m - 11)))
      return true;
   return false;
}
int main(){
   string S = "5818005553985";
   cout << solve(S) << endl;
}

Input

"5818005553985"

Output

1
raja
Updated on 11-Mar-2022 07:17:41

Advertisements