Just get one character at a time:
int num = getc(stdin) - '0';
The subtraction of '0' is to turn a character into a number. Obviously error checking is left as an exercise.
質問
NOTE: Please don't write the solution(i.e. algorithmic logic) for this problem.
Yesterday Chef had a great party and doesn't remember the way he celebreated it. But he found a strange paper in his kitchen containing n digits (lets give them indices from 1 to n and name them a1, a2 ... aN).
Chef remembers that he played such game:
On each step he choose an index x from 1 to n.
For all indices y (y < x) he calculated the difference by = ax - ay.
Then he calculated B1 - sum of all by which are greater than 0 and B2 - sum of all by which are less than 0.
The answer for this step is B1 - B2.
Chef remembers the game, but forgot the answer. Please, help him! Input
The first line contains two integers n, m denoting the number of digits and number of steps. The second line contains n digits (without spaces) a1, a2, ..., an.
Each of next m lines contains single integer x denoting the index for current step.
Output
For each of m steps print single number in a line - answer of the step.
Constraints
1 ≤ n, m ≤ 10^5
0 ≤ ai ≤ 9
1 ≤ x ≤ n
now how do i take n digit input?i mean how do i use scanf code in this.i dont5 know exact value of n so i cant declare those many variables.does it mean that i take a single digit input?
解決
Just get one character at a time:
int num = getc(stdin) - '0';
The subtraction of '0' is to turn a character into a number. Obviously error checking is left as an exercise.
他のヒント
(assuming n digit input is a string, with n characters) Use dynamic memory allocation and a customized scanf
formatter:
int n = 0;
char* digits = NULL;
char format[256];
printf("n=");
scanf("%d", &n);
digits = calloc(n + 1, 1); /* for the terminator 0 to be initialized*/
snprintf(format, 256, "%%%ds", n); /* to not to cause an overflow */
if(NULL == digits)
{
printf("Not enough memory");
exit(1);
}
scanf(format, digits);
printf("%s", digits);
// DO your algorithm here
free(digits);
@user3424954 read the problem statement again it is clearly mention first line inputs n which is the length of the numeral string. You can try using *scanf("%s",array_name);*