Longest Subsequence from a numeric String divisible by K | Function to if the integer representation of the current string is divisible by K ; Stores the integer representation of the string ; Check if the num is divisible by K ; Function to find the longest subsequence which is divisible by K ; If the number is divisible by K ; If current number is the maximum obtained so far ; Include the digit at current index ; Exclude the digit at current index ; Driver Code ; Printing the largest number which is divisible by K ; If no number is found to be divisible by K
function isdivisible ( newstr , K ) { var num = 0 ; for ( var i = 0 ; i < newstr . length ; i ++ ) { num = num * 10 + newstr [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ; } if ( num % K == 0 ) return true ; else return false ; } function findLargestNo ( str , newstr , ans , index , K ) { if ( index == str . length ) { if ( isdivisible ( newstr , K ) ) { if ( ( ans < newstr && ans . length == newstr . length ) newstr . length > ans . length ) { ans = newstr ; } } return ans ; } var x = newstr + str [ index ] ; ans = findLargestNo ( str , x , ans , index + 1 , K ) ; ans = findLargestNo ( str , newstr , ans , index + 1 , K ) ; return ans ; } var str = " " ; var ans = " " , newstr = " " ; var K = 8 ; ans = findLargestNo ( str , newstr , ans , 0 , K ) ; if ( ans != " " ) document . write ( ans ) else document . write ( - 1 )