Minimum increments by 1 or K required to convert a string into another given string | Java program for the above approach ; Function to count minimum increments by 1 or K required to convert X to Y ; Convert String to character array ; Traverse the string X ; Case 1 ; Case 2 ; Add the difference / K to the count ; Add the difference % K to the count ; Case 3 ; Add the difference / K to the count ; Add the difference % K to the count ; Print the answer ; Driver Code
import java . io . * ; class GFG { public static void countOperations ( String X , String Y , int K ) { char ch1 [ ] = X . toCharArray ( ) ; char ch2 [ ] = Y . toCharArray ( ) ; int count = 0 ; for ( int i = 0 ; i < X . length ( ) ; i ++ ) { int c = 0 ; if ( ch1 [ i ] == ch2 [ i ] ) continue ; else if ( ch1 [ i ] < ch2 [ i ] ) { if ( ( ( int ) ch2 [ i ] - ( int ) ch1 [ i ] ) >= K ) { c = ( ( int ) ch2 [ i ] - ( int ) ch1 [ i ] ) / K ; } c += ( ( int ) ch2 [ i ] - ( int ) ch1 [ i ] ) % K ; } else { int t = 90 - ( int ) ch1 [ i ] ; t += ( int ) ch2 [ i ] - 65 + 1 ; if ( t >= K ) c = t / K ; c += ( t % K ) ; } count += c ; } System . out . print ( count ) ; } public static void main ( String [ ] args ) { String X = " ABCT " , Y = " PBDI " ; int K = 6 ; countOperations ( X , Y , K ) ; } }