Minimum number of swaps required to make a number divisible by 60 | C ++ program to find minimum number of swap operations required ; Function that print minimum number of swap operations required ; Condition if more than one zero exist ; Condition if zero_exist ; Computing total sum of all digits ; Condition if zero does not exist or the sum is not divisible by 3 ; Condition to find a digit that is multiple of 2 other than one zero ; Condition if multiple of 2 do not exist ; Condition for zero swaps means the number is already is divisible by 60 ; Condition for only one swap ; Otherwise 2 swaps required ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void MinimumSwapOperations ( string s ) { bool zero_exist = false ; bool multiple_of_2 = false ; int sum = 0 ; int index_of_zero ; bool more_zero = false ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { int val = s [ i ] - '0' ; if ( zero_exist == true ) more_zero = true ; if ( val == 0 ) { zero_exist = true ; index_of_zero = i ; } sum += val ; } if ( zero_exist == false sum % 3 != 0 ) { cout << " - 1" << " STRNEWLINE " ; return ; } for ( int i = 0 ; i < s . length ( ) ; i ++ ) { int val = s [ i ] - '0' ; if ( val % 2 == 0 && i != index_of_zero ) multiple_of_2 = true ; } if ( multiple_of_2 == false ) { cout << " - 1" << " STRNEWLINE " ; return ; } int last_val = s [ s . length ( ) - 1 ] - '0' ; int second_last_val = s [ s . length ( ) - 2 ] - '0' ; if ( last_val == 0 && second_last_val % 2 == 0 ) cout << 0 << " STRNEWLINE " ; else if ( ( last_val == 0 && second_last_val % 2 != 0 ) || ( last_val % 2 == 0 && second_last_val == 0 ) ) cout << 1 << " STRNEWLINE " ; else if ( more_zero == true && ( last_val == 0 && second_last_val % 2 != 0 ) ) cout << 1 << " STRNEWLINE " ; else cout << 2 << " STRNEWLINE " ; } int main ( ) { string N = "20" ; MinimumSwapOperations ( N ) ; return 0 ; }