![]() |
VOOZH | about |
Given a non-negative integer represented in the form of a numeric string str. Remove zero or more characters from the string such that the number becomes divisible by 8. If it is possible, print the string after removing the characters otherwise print -1.
Examples:
Input: str = "3454"
Output: 344
After removing '5', string becomes 344 which is divisible by 8.
Input: str = "111"
Output: -1
Approach: Considering the divisibility rule of 8, we just need to check if the number formed by last 3 characters of str is divisible by 8 or not. Thus, we can iterate over all multiples of 8 upto 1000 and check if any of the multiple exists as a sub-sequence in the given string, then that multiple is our required answer. Otherwise, there exists no answer since all multiples of 8 greater than 1000 also needs to have the number (formed from last 3 digits) which has already been checked.
Steps to solve the problem:
Below is the implementation of the above approach:
344
Time Complexity: O(n)
Auxiliary Space: O(1)