Print digit 's position to be removed to make a 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 Code
< ? php function greatest ( $ s ) { $ n = strlen ( $ s ) ; $ a [ $ n ] = array ( ) ; $ sum = 0 ; for ( $ 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 ) { echo " - 1" , " STRNEWLINE " ; } else { echo $ n , " STRNEWLINE " ; } } else { $ re = $ sum % 3 ; $ del = -1 ; $ flag = 0 ; for ( $ 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 ) echo - 1 , " STRNEWLINE " ; else { echo $ del + 1 , " STRNEWLINE " ; } } } $ s = "7510222" ; greatest ( $ s ) ; ? >