Print digit 's position to be removed to make a number divisible by 6 | C ++ program to print digit 's position to be removed to make number divisible by 6 ; function to print the number divisible by 6 after exactly removing a digit ; stores the sum of all elements ; traverses the string and converts string to number array and sums up ; if ( a [ n - 1 ] % 2 ) ODD CHECK ; if second last is odd or sum of n - 1 elements are not divisible by 3. ; second last is even and print n - 1 elements removing last digit ; last digit removed ; counter to check if any element after removing , its sum % 3 == 0 ; traverse till second last element ; to check if any element after removing , its sum % 3 == 0 ; the leftmost element ; break at the leftmost element ; stores the right most element ; if no element has been found as a [ i + 1 ] > a [ i ] ; if second last is even , then remove last if ( sum - last ) % 3 == 0 ; if no element which on removing gives sum % 3 == 0 ; driver program to test the above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void greatest ( string s ) { int n = s . length ( ) ; int a [ n ] ; int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { a [ i ] = s [ i ] - '0' ; sum += a [ i ] ; } { if ( a [ n - 2 ] % 2 != 0 or ( sum - a [ n - 1 ] ) % 3 != 0 ) { cout << " - 1" << endl ; } else { cout << n << endl ; } } else { int re = sum % 3 ; int del = -1 ; int flag = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( ( a [ i ] ) % 3 == re ) { if ( a [ i + 1 ] > a [ i ] ) { del = i ; flag = 1 ; break ; } else { del = i ; } } } if ( flag == 0 ) { if ( a [ n - 2 ] % 2 == 0 and re == a [ n - 1 ] % 3 ) del = n - 1 ; } if ( del == -1 ) cout << -1 << endl ; else { cout << del + 1 << endl ; } } } int main ( ) { string s = "7510222" ; greatest ( s ) ; return 0 ; }