The function/method findSeriesSum accepts an argument str representing a string value. The string str contains a series of integers but some integers are denoted by their binary representations.
The function/method findSeriesSum must find the decimal value for each binary representation in the given string. Then the function must return an integer representing the sum of all the integers present in the given series.
Your task is to implement the function findSeriesSum so that the program runs successfully.
IMPORTANT: Do not write the main() function as it is already defined.
Boundary Condition(s):
1 <= Each integer value in the series <= 10^7
Example Input/Output 1:
Input:
45 32 1010 5 10111 60
Output:
175
Explanation:
In the given series, two integers are denoted by their binary representations.
1010 -> 10
10111 -> 23
Sum = 45 + 32 + 10 + 5 + 23 + 60 = 175.
Example Input/Output 2:
Input:
10 111 1005 1114 101
Output:
2133
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
int findSeriesSum(char *str)
{
char *token = strtok(str," ");
int i,j,n,sum=0;
while(token!=NULL){
char s[100];
strcpy(s,token);
//printf("%s-",s);
n=strlen(s);
int c=0;
for(i='9';i>='2';i--){
for(j=0;j<n;j++){
if(s[j]==i){
c++;
}
}
}
if(c>0){
sum+=atoi(s);
}
else{
int k=0,num=0;
for(i=n- 1;i>=0;i--){
int l;
l=pow(2,k);
num+=l*(s[i]-'0');
k++;
}
sum+=num;
}
token=strtok(NULL," ");
}
return sum;
}
int main()
{
char str[101];
scanf("%[^nr]", str);
printf("%d", findSeriesSum(str));
return 0;
}
Leave a Reply