Open In App

Remove characters from a numeric string such that string becomes divisible by 8

Last Updated : 07 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  •  In a function checkSub that takes two string arguments, sub and s.
    • Initialize a variable j to 0.
    • Iterate over the characters of s using a for loop from i = 0 to i < s.size().
      • Check if the jth character of sub is equal to the ith character of s than  increment j by 1.
    • if j is equal to the length of sub, return true. Otherwise, return false.
  •  In a function getMultiple that takes a string argument s.
    • Iterate over all multiples of 8 from 0 to 999 using a for loop from i = 0 to i < 1000 by incrementing i by 8.
      • Check if the current multiple i exists as a subsequence in the given string s using the checkSub function defined earlier.
      • If i exists as a subsequence, return i.
    • If no multiple of 8 is found, return -1.

Below is the implementation of the above approach: 

C++




// C++ program to remove digits from a
// numeric string such that the number
// becomes divisible by 8
#include <bits/stdc++.h>
using namespace std;
 
// Function that return true if sub
// is a sub-sequence in s
int checkSub(string sub, string s)
{
    int j = 0;
    for (int i = 0; i < s.size(); i++)
        if (sub[j] == s[i])
            j++;
    return j == (int)sub.size();
}
 
// Function to return a multiple of 8
// formed after removing 0 or more characters
// from the given string
int getMultiple(string s)
{
    // Iterate over all multiples of 8
    for (int i = 0; i < 1e3; i += 8) {
 
        // If current multiple
        // exists as a subsequence
        // in the given string
        if (checkSub(to_string(i), s))
            return i;
    }
 
    return -1;
}
 
// Driver Code
int main()
{
    string s = "3454";
    cout << getMultiple(s);
 
    return 0;
}


Java




// Java program to remove digits from a
// numeric string such that the number
// becomes divisible by 8
 
class GFG
{
 
    // Function that return true if sub
    // is a sub-sequence in s
    static boolean checkSub(String sub, String s)
    {
        int j = 0;
        for (int i = 0; i < s.length(); i++)
            if (sub.charAt(j) == s.charAt(i))
                j++;
                 
        return j == sub.length();
    }
     
    // Function to return a multiple of 8
    // formed after removing 0 or more characters
    // from the given string
    static int getMultiple(String s)
    {
        // Iterate over all multiples of 8
        for (int i = 0; i < 1E3; i += 8)
        {
     
            // If current multiple
            // exists as a subsequence
            // in the given string
            if (checkSub(Integer.toString(i), s))
                return i;
        }
        return -1;
    }
 
    // Driver Code
    public static void main (String[] args)
    {
            String s = "3454";
            System.out.println(getMultiple(s));
    }
}
 
// This code is contributed by mits


Python3




# Python3 program to remove digits from
# a numeric string such that the number
# becomes divisible by 8
import math as mt
 
# Function that return true if sub
# is a sub-sequence in s
def checkSub(sub, s):
 
    j = 0
    for i in range(len(s)):
        if (sub[j] == s[i]):
            j += 1
 
    if j == int(len(sub)):
        return True
    else:
        return False
 
# Function to return a multiple of 8
# formed after removing 0 or more
# characters from the given string
def getMultiple(s):
     
    # Iterate over all multiples of 8
    for i in range(0, 10**3, 8):
 
        # If current multiple
        # exists as a subsequence
        # in the given string
        if (checkSub(str(i), s)):
            return i
 
    return -1
 
# Driver Code
s = "3454"
print(getMultiple(s))
 
# This code is contributed
# by Mohit Kumar 29


C#




// C# program to remove digits from a
// numeric string such that the number
// becomes divisible by 8
using System;
 
class GFG
{
 
    // Function that return true if sub
    // is a sub-sequence in s
    static bool checkSub(string sub, string s)
    {
        int j = 0;
        for (int i = 0; i < s.Length; i++)
            if (sub[j] == s[i])
                j++;
                 
        return j == sub.Length;
    }
     
    // Function to return a multiple of 8
    // formed after removing 0 or more characters
    // from the given string
    static int getMultiple(string s)
    {
        // Iterate over all multiples of 8
        for (int i = 0; i < 1e3; i += 8)
        {
     
            // If current multiple
            // exists as a subsequence
            // in the given string
            if (checkSub(i.ToString(), s))
                return i;
        }
        return -1;
    }
 
    // Driver Code
    static void Main()
    {
            string s = "3454";
            Console.WriteLine(getMultiple(s));
    }
}
 
// This code is contributed by Ryuga


PHP




<?php
// PHP program to remove digits from a
// numeric string such that the number
// becomes divisible by 8
 
// Function that return true if sub
// is a sub-sequence in s
function checkSub($sub, $s)
{
    $j = 0;
    for ($i = 0; $i < strlen($s); $i++)
        if ($sub[$j] == $s[$i])
            $j++;
    return $j == strlen($sub);
}
 
// Function to return a multiple of 8
// formed after removing 0 or more
// characters from the given string
function getMultiple($s)
{
    // Iterate over all multiples of 8
    for ($i = 0; $i < 1e3; $i += 8)
    {
 
        // If current multiple
        // exists as a subsequence
        // in the given string
        if (checkSub((string)($i), $s))
            return $i;
    }
 
    return -1;
}
 
// Driver Code
$s = "3454";
echo getMultiple($s);
 
// This code is contributed
// by Akanksha Rai


Javascript




<script>
 
    // JavaScript program to remove digits from a
    // numeric string such that the number
    // becomes divisible by 8
     
    // Function that return true if sub
    // is a sub-sequence in s
    function checkSub(sub, s)
    {
        let j = 0;
        for (let i = 0; i < s.length; i++)
            if (sub[j] == s[i])
                j++;
                   
        return j == sub.length;
    }
       
    // Function to return a multiple of 8
    // formed after removing 0 or more characters
    // from the given string
    function getMultiple(s)
    {
        // Iterate over all multiples of 8
        for (let i = 0; i < 1e3; i += 8)
        {
       
            // If current multiple
            // exists as a subsequence
            // in the given string
            if (checkSub(i.toString(), s))
                return i;
        }
        return -1;
    }
     
    let s = "3454";
      document.write(getMultiple(s));
     
</script>


Output: 

344

 

Time Complexity: O(n)
Auxiliary Space: O(1)



Similar Reads

Remove uppercase, lowercase, special, numeric, and non-numeric characters from a String
Given string str of length N, the task is to remove uppercase, lowercase, special, numeric, and non-numeric characters from this string and print the string after the simultaneous modifications. Examples: Input: str = “GFGgfg123$%” Output: After removing uppercase characters: gfg123$% After removing lowercase characters: GFG123$% After removing spe
10 min read
Remove minimum elements from the array such that 2*min becomes more than max
Given an array of size N. The task is to remove minimum elements from the array such that twice of minimum number is greater than the maximum number in the modified array. Print the minimum number of elements removed.Examples: Input: arr[] = {4, 5, 100, 9, 10, 11, 12, 15, 200} Output: 4 Remove 4 elements (4, 5, 100, 200) so that 2*min becomes more
6 min read
Remove minimum elements from either side such that 2*min becomes more than max
Given an unsorted array, trim the array such that twice of minimum is greater than maximum in the trimmed array. Elements should be removed either end of the array.Number of removals should be minimum. Examples: arr[] = {4, 5, 100, 9, 10, 11, 12, 15, 200} Output: 4 We need to remove 4 elements (4, 5, 100, 200) so that 2*min becomes more than max. a
27 min read
Remove minimum elements from either side such that 2*min becomes more than max | Set 2
Given an unsorted array, trim the array such that twice of minimum is greater than the maximum in the trimmed array. Elements should be removed from either end of the array. The number of removals should be minimum. Examples: Input: arr[] = {4, 5, 100, 9, 10, 11, 12, 15, 200} Output: 4 We need to remove 4 elements (4, 5, 100, 200) so that 2*min bec
17 min read
Count of characters in str1 such that after deleting anyone of them str1 becomes str2
Given two strings str1 and str2, the task is to count the characters in str1 such that after removing any one of them str1 becomes identical to str2. Also, print positions of these characters. If it is not possible then print -1.Examples: Input: str1 = "abdrakadabra", str2 = "abrakadabra" Output: 1 The only valid character is at index 2 i.e. str1[2
6 min read
Ways to remove one element from a binary string so that XOR becomes zero
Given a binary string, task is to erase exactly one integer in the array so that the XOR of the remaining numbers is zero. The task is to count number of ways to remove one element so that XOR of that string become ZERO. Examples : Input : 10000 Output : 1 We only have 1 ways to Input : 10011 Output : 3 There are 3 ways to make XOR 0. We can remove
5 min read
Number of positions where a letter can be inserted such that a string becomes palindrome
Given a string str, we need to find the no. of positions where a letter(lowercase) can be inserted so that string becomes a palindrome. Examples: Input : str = "abca" Output : possible palindromic strings: 1) acbca (at position 2) 2) abcba (at position 4) Hence, the output is 2. Input : str = "aaa" Output : possible palindromic strings: 1) aaaa 2)
11 min read
Convert the array such that the GCD of the array becomes 1
Given an array of positive elements and a positive integer k, the task is to convert the GCD of the array to 1. To make it possible, only one operation is allowed any number of times i.e. choose any element of the array &amp; divide with a number d where d &lt;= k. Examples: Input : arr = {10, 15, 30}, k = 6 Output : Yes Divide all the elements of
9 min read
Find third number such that sum of all three number becomes prime
Given two numbers A and B. The task is to find the smallest positive integer greater than or equal to 1 such that the sum of all three numbers become a prime number.Examples: Input: A = 2, B = 3 Output: 2 Explanation: The third number is 2 because if we add all three number the sum obtained is 7 which is a prime number.Input: A = 5, B = 3 Output: 3
5 min read
Number formed by deleting digits such that sum of the digits becomes even and the number odd
Given a non-negative number N, the task is to convert the number by deleting some digits of the number, such that the sum of the digits becomes even but the number is odd. In case there is no possible number, then print -1.Note: There can be multiple numbers possible for a given N.Examples: Input: N = 18720 Output: 17 Explanation: After Deleting 8,
5 min read