Longest Subsequence from a numeric String divisible by K | Java program for the above approach ; 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
import java . util . * ; import java . lang . * ; class GFG { static boolean isdivisible ( StringBuilder newstr , long K ) { long num = 0 ; for ( int i = 0 ; i < newstr . length ( ) ; i ++ ) { num = num * 10 + newstr . charAt ( i ) - '0' ; } if ( num % K == 0 ) return true ; else return false ; } static void findLargestNo ( String str , StringBuilder newstr , StringBuilder ans , int index , long K ) { if ( index == str . length ( ) ) { if ( isdivisible ( newstr , K ) ) { if ( ( newstr . toString ( ) . compareTo ( ans . toString ( ) ) > 0 && ans . length ( ) == newstr . length ( ) ) || newstr . length ( ) > ans . length ( ) ) { ans . setLength ( 0 ) ; ans . append ( newstr ) ; } } return ; } StringBuilder x = new StringBuilder ( newstr . toString ( ) + str . charAt ( index ) ) ; findLargestNo ( str , x , ans , index + 1 , K ) ; findLargestNo ( str , newstr , ans , index + 1 , K ) ; } public static void main ( String [ ] args ) { String str = "121400" ; StringBuilder ans = new StringBuilder ( ) , newstr = new StringBuilder ( ) ; long K = 8 ; findLargestNo ( str , newstr , ans , 0 , K ) ; if ( ans . toString ( ) != " " ) System . out . println ( ans ) ; else System . out . println ( - 1 ) ; } }