text: Sum of all subsequences of a number | CPP program to find the sum of elements present in all subsequences ; Returns numeric value of a subsequence of s . The subsequence to be picked is decided using bit pattern of num ( We pick all thosedigits for which there is a set bit in num ) ; Initialize the result ; till n != 0 ; if i - th bit is set then add this number ; right shift i ; function to find combined sum of all individual subsequence sum ; length of string ; stores the combined ; 2 ^ n - 1 subsequences ; loop for all subsequences ; returns the combined sum ; driver code
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; int findSubSequence ( string s , int num ) { int res = 0 ; int i = 0 ; while ( num ) { if ( num & 1 ) res += s [ i ] - '0' ; i ++ ; num = num >> 1 ; } return res ; } int combinedSum ( string s ) { int n = s . length ( ) ; int c_sum = 0 ; int range = ( 1 << n ) - 1 ; for ( int i = 0 ; i <= range ; i ++ ) c_sum += findSubSequence ( s , i ) ; return c_sum ; } int main ( ) { string s = "123" ; cout << combinedSum ( s ) ; return 0 ; }