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 ; 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
function greatest ( s ) { let n = s . length ; let a = new Array ( n ) ; let sum = 0 ; for ( let i = 0 ; i < n ; i ++ ) { a [ i ] = s [ i ] - ' ' ; sum += a [ i ] ; } if ( a [ n - 1 ] % 2 ) { if ( a [ n - 2 ] % 2 != 0 || ( sum - a [ n - 1 ] ) % 3 != 0 ) { document . write ( " " + " " ) ; } else { document . write ( n + " " ) ; } } else { let re = sum % 3 ; let del = - 1 ; let flag = 0 ; for ( let 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 && re === a [ n - 1 ] % 3 ) del = n - 1 ; } if ( del === - 1 ) document . write ( - 1 + " " ) ; else { document . write ( del + 1 + " " ) ; } } } let s = " " ; greatest ( s ) ;