Pergunta de entrevista da empresa Amazon
Using only putchar how would you print out the ascii values for each digit in an integer. For example if the integer was 123, then you would want to print the ascii values for 1, 2, and 3.
Respostas da entrevista
void printASCII(int src)
if (src > 9) {
printASCII(src/10);
}
putchar('0' + (src % 10));
}
void print_ascii(int n)
{
while(n)
{
int k = (n%10)+'0';
n/=10;
putchar(k);
printf("\n");
}
}
I used a recursive method involving modulus and division by 10. Not hard, just stressful writing it on paper in an interview.
Ah...the above code would just print the numbers itself not ascii values
Could be fixed by adding ascii value of 0 char
ie. putchar(*input + '0');
input++;
void printAscii( char *input)
{
while(input)
{
putchar(*input++);
}
}
This should work as well....printing each char as an integer would give its ascii value