I just came home from a job interview, and the interviewer asked me to write a program:
It should, count from 1 to 100, and print...
If it was multiple of 3, "ping"
If it was multiple of 5, "pong"
Else, print the number.
If it was multiple of 3 AND 5 (like 15), it should print "ping" and "pong".
I chose Javascript, and came up with this:
for (x=1; x <= 100; x++){
if( x % 3 == 0 ){
write("ping")
}
if( x % 5 == 0 ){
write("pong")
}
if( ( x % 3 != 0 ) && ( x % 5 != 0 ) ){
write(x)
}
}
Actualy, I left very unhappy with my solution, but I can't figure out a better one.
Does anyone knows a better way to do that?
It's checking twice, I didn't like it.
I ran some tests here at home, without success, this is the only one that returns the correct answer...
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…