Possible Duplicate: Help with C puzzle [1]
This morning i had a job interview and they gave me this problem:
You should change one character to print "*" 42 times. You can replace, add or remove ONLY one character.
Still i cant figured it, i've tried over and over again.
#include <stdio.h>
main(){
int i,n = 42;
for(i = 0; i < n; i--){
printf("*");
}
}
One option would be to change the <
to a +
:
#include <stdio.h>
main(){
int i,n = 42;
for(i = 0; i + n; i--){
printf("*");
}
}
The reason this works is that C treats nonzero values as "true" and zero values as "false." The value of i + n
starts at 42 and then counts down 41, 40, 39, ..., 1, 0. When it hits zero, it must mean that i == -n
, at which point you're done.
-i
or n--
- Henk Holterman
#include <stdio.h>
main(){
int i,n = 42;
for(i = 0; -i < n; i--){ //added a minus here
printf("*");
}
}
But to be honest, I think that this is a silly interview question.
for(i = 0; i < n; n--){
printf("*");
}
Looks like you change the i--
to n--
.
Seems like a strange interview question. What was it for, if you don't mind me asking?
What about changing the -
to a +
? :)
I changed the source a tiny little bit.
$ cat 4927230.c #include <stdio.h> int main(void) { int i, n = 42; for (i = 0; i < n; i--) { printf("*"); } puts(""); return 0; } $ tr \- \+ < 4927230.c | gcc -xc - && ./a.out ****************************************** $
hehe
tr
does, scratches his/her head, and says "umm... you pass". Total score = +1 - Mike
How about:
for(i = 0; -i < n; i--) {
^
That's easy:
#include <stdio.h>
main(){
int i,n = 42;
for(i = 0; i < n; n--){
printf("*");
}
}
While this is a "puzzle" rather than a programming task, I think it is actually a rather good interview question, as it tests a number of skills valuable in a programmer. If you can't solve this, then you may have a lot of trouble reasoning about complex code.
The first thing I noted is that i is initialized twice, so its initialization to 42 is irrelevant unless the second initialization is eliminated, e.g. by changing it to i + 0. The next thing I noted is that we're stuck with -- as it cannot be usefully modified by a single character. So we're decrementing a counter but using < for the test, so we need to do an inversion of some sort. -i < n does that handily, as does n-- by decrementing the limit rather than the counter. The i + n solution, which is equivalent to -i != n, is harder to come up with.
-
flipping a<
or adding a!
... That said I still couldn't work it out. Seems like a fair test of my (in)ability to quickly gauge what tools are available and how to apply them within narrow constraints. - J. Winchesteri--
=>i++
) so you have code that is a little bit more readable". If that doesn't get you the points, you don't want the job anyway. - JeremyP