Where did I go wrong in the following submission?Can someone please explain?Thanks.This is my solution
There are several things wrong with your submission:
-
for(i=0; i < sizeof(array); i++)
you created an array of size 1000 and now reading the entire array while you should be reading only the string. Usestrlen
instead ofsizeof
. -
sum+=int array[i]
you are adding ASCII values of digit, while you should be adding the magnitude, useint(ar[i] - '0')
instead. -
printf("%d",sum)
you need to print the answer for each test case in a new line, useprintf("%d\n", sum)
instead.
Correct code:
int main() {
int T;
scanf("%d",&T);
while(T--) {
char array[1000];
scanf("%s",array);
int sum = 0;
for(int i = 0 ; i < strlen(array); i++) {
if(isdigit(array[i])) {
sum += int(array[i] - '0');
}
}
printf("%d\n", sum);
}
return 0;
}
Thanks buddy