C++ Program to remove Characters from a Numeric String Such That String Becomes Divisible by 8


Given a number in the form of a string, we need to find where to make it divisible by eight after deleting zero or more elements. In other words, we need to find whether there is a subsequence of the string, which is divisible by 8. Return the modified string or -1 if it is not possible.

Any number whose last three digits are divisible by 8 is also divisible by 8. For example, 56992992 and 476360 are divisible by 8, but 2587788 is not. If the result is a whole number, then the original number is divisible by 8.

We can iterate from 0 to 1000 with multiples of 8 like 0, 8, 16, 24, 32 … 1000 and check if this number exists in the given string as a subsequence. Let’s take two strings, one which can be converted to a string divisible by eight and one which cannot be, and find the output in each case.

Example

#include <iostream>
using namespace std;
int checkIfSubstringExist(string req, string given) {
   int index = 0;
   for (char ch : given) {
      if (req[index] == ch) {
         index++;
      }
   }
   return index == (int)req.size();
}
string solve(string s) {
   for (int i = 0; i < 1e3; i += 8) {
      string num = to_string(i);
      if (checkIfSubstringExist(num, s)) {
         return num;
      }
   }
   return "-1";
}
int main() {
   // the string “95256” can be converted to a string divisible by 8
   // the string “74513” cannot be converted to a string divisible by 8
   // let’s run our code to find the output in each case
   string s1 = "95258", s2="74516";
   cout << solve(s1) << "\n" << solve(s2) << endl;
   return 0;
}

Output

8
16

As you can see in the above output, 9525 is removed from 95258, and 745 is removed from 74516 to make the left number divisible by 8.

Conclusion

As we see, after the simple observations, we just needed to check if the subset exists or not. We check the string for the subsequence, and in the worst case, it will check the entire string, So if we are given a numeric string with length n, so the worst time complexity is O(126*n) which is O(n).

Updated on: 18-May-2022

153 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements