Check if sum of array can be made equal to X by removing either the first or last digits of every array element | C ++ program for the above approach ; Utility Function to check if the sum of the array elements can be made equal to X by removing either the first or last digits of every array element ; Base Case ; Convert arr [ i ] to string ; Remove last digit ; Remove first digit ; Recursive function call ; Function to check if sum of given array can be made equal to X or not ; Driver code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool makeSumX ( int arr [ ] , int X , int S , int i , int N ) { if ( i == N ) { return S == X ; } string a = to_string ( arr [ i ] ) ; int l = stoi ( a . substr ( 0 , a . length ( ) - 1 ) ) ; int r = stoi ( a . substr ( 1 ) ) ; bool x = makeSumX ( arr , X , S + l , i + 1 , N ) ; bool y = makeSumX ( arr , X , S + r , i + 1 , N ) ; return ( x y ) ; } void Check ( int arr [ ] , int X , int N ) { if ( makeSumX ( arr , X , 0 , 0 , N ) ) { cout << " Yes " ; } else { cout << " No " ; } } int main ( ) { int arr [ ] = { 545 , 433 , 654 , 23 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int X = 134 ; Check ( arr , X , N ) ; return 0 ; }