C++ Program to check string can be reduced to 2022 or not



Suppose we have a numeric string S with n digits. We perform the following operation with the string S, no more than once. We select two numbers i and j (1 ≤ i ≤ j ≤ n) and removes characters from S string from positions i to j. We have to check whether the string S can be reduced to 2022 in no more than one operations or not.

Problem Category

To solve this problem, we need to manipulate strings. Strings in a programming language are a stream of characters that are stored in a particular array-like data type. Several languages specify strings as a specific data type (eg. Java, C++, Python); and several other languages specify strings as a character array (eg. C). Strings are instrumental in programming as they often are the preferred data type in various applications and are used as the datatype for input and output. There are various string operations, such as string searching, substring generation, string stripping operations, string translation operations, string replacement operations, string reverse operations, and much more. Check out the links below to understand how strings can be used in C/C++.

https://www.tutorialspoint.com/cplusplus/cpp_strings.htm

https://www.tutorialspoint.com/cprogramming/c_strings.htm

So, if the input of our problem is like S = "2548022", then the output will be True, because we can remove from index 1 to 3.

Steps

To solve this, we will follow these steps −

n := size of S
for initialize i := 0, when i <= 4, update (increase i by 1), do:
   temp := (substring of S from 0 to ith character) concatenate (substring of S from index up to [n - 4 + i]
   if temp is same as "2022", 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 n = S.size();
   for (int i = 0; i <= 4; i++){
      string temp = S.substr(0, i) + S.substr(n - 4 + i);
      if (temp == "2022")
         return true;
   }
   return false;
}
int main(){
   string S = "2548022";
   cout << solve(S) << endl;
}

Input

2548022

Output

1

Advertisements