Minimum number of digits required to be removed to make a number divisible by 4 | C ++ program for the above approach ; Function to count the minimum number of digits required to be removed to make a given number divisible by 4 ; Store the size of the string ; Stores the required result ; Check for every pair of digits if the number formed by them is divisible by 4 or not ; Store s [ i ] in a variable ; If it is divisible by 2 ; Store the number formed by s [ j ] and s [ i ] ; Check if it is divisible by 4 ; Store the number of digits required to be deleted ; Update ans ; If value of ans is unchanged , then check if any s [ i ] is divisible by 4 ; If true , update ans to n - 1 ; Print the result ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minimumDeletions ( string s ) { int n = s . length ( ) ; int ans = n ; for ( int i = n - 1 ; i >= 0 ; i -- ) { int t = s [ i ] - '0' ; if ( t % 2 == 0 ) { for ( int j = i - 1 ; j >= 0 ; j -- ) { int num = ( s [ j ] - '0' ) * 10 + t ; if ( num % 4 == 0 ) { int k1 = i - j - 1 ; int k2 = n - i - 1 ; ans = min ( ans , k1 + k2 ) ; } } } } if ( ans == n ) { for ( int i = 0 ; i < n ; i ++ ) { int num = s [ i ] - '0' ; if ( num % 4 == 0 ) { ans = n - 1 ; } } } cout << ans ; } int main ( ) { string str = "12367" ; minimumDeletions ( str ) ; return 0 ; }