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

C++Server Side ProgrammingProgramming

<p>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 &le; i &le; j &le; 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.</p><h2>Problem Category</h2><p>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++.</p><p><a href="https://www.tutorialspoint.com/cplusplus/cpp_strings.htm" rel="nofollow" target="_blank">https://www.tutorialspoint.com/cplusplus/cpp_strings.htm</a></p><p><a href="https://www.tutorialspoint.com/cprogramming/c_strings.htm" rel="nofollow" target="_blank">https://www.tutorialspoint.com/cprogramming/c_strings.htm</a></p><p>So, if the input of our problem is like S = &quot;2548022&quot;, then the output will be True, because we can remove from index 1 to 3.</p><h2>Steps</h2><p>To solve this, we will follow these steps &minus;</p><pre class="just-code notranslate language-cpp" data-lang="cpp">n := size of S for initialize i := 0, when i &lt;= 4, update (increase i by 1), do: &nbsp; &nbsp;temp := (substring of S from 0 to ith character) concatenate (substring of S from index up to [n - 4 + i] &nbsp; &nbsp;if temp is same as &quot;2022&quot;, then: &nbsp; &nbsp; &nbsp; return true return false</pre><h2>Example</h2><p>Let us see the following implementation to get better understanding &minus;</p><pre class="demo-code notranslate language-cpp" data-lang="cpp">#include &lt;bits/stdc++.h&gt; using namespace std; bool solve(string S){ &nbsp; &nbsp;int n = S.size(); &nbsp; &nbsp;for (int i = 0; i &lt;= 4; i++){ &nbsp; &nbsp; &nbsp; string temp = S.substr(0, i) + S.substr(n - 4 + i); &nbsp; &nbsp; &nbsp; if (temp == &quot;2022&quot;) &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return true; &nbsp; &nbsp;} &nbsp; &nbsp;return false; } int main(){ &nbsp; &nbsp;string S = &quot;2548022&quot;; &nbsp; &nbsp;cout &lt;&lt; solve(S) &lt;&lt; endl; }</pre><h2>Input</h2><pre class="result notranslate">2548022</pre><h2>Output</h2><pre class="result notranslate">1</pre>
raja
Updated on 08-Apr-2022 08:18:57

Advertisements