Number of ways to form a number with maximum Ks in it | C ++ program for the above approach ; Function to calculate number of ways a number can be formed that has the maximum number of Ks ; convert to string ; calculate length of subarrays that can contribute to the answer ; count length of subarray where adjacent digits add up to K ; Current subarray can contribute to the answer only if it is odd ; return the answer ; Driver code ; Input ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int noOfWays ( int N , int K ) { string S = to_string ( N ) ; int ans = 1 ; for ( int i = 1 ; i < S . length ( ) ; i ++ ) { int count = 1 ; while ( i < S . length ( ) && S [ i ] - '0' + S [ i - 1 ] - '0' == K ) { count ++ ; i ++ ; } if ( count % 2 ) ans *= ( count + 1 ) / 2 ; } return ans ; } int main ( ) { int N = 1454781 ; int K = 9 ; cout << noOfWays ( N , K ) << endl ; }