从1到100,打印“ping”如果是3,“pong”的倍数。如果是5的倍数,或者打印数字 [英] From 1 to 100, print "ping" if multiple of 3, "pong" if multiple of 5, or else print the number
问题描述
我刚从求职面试回家,面试官要我写一个程序:
I just came home from a job interview, and the interviewer asked me to write a program:
它应该从1到100计算,并打印.. 。
It should, count from 1 to 100, and print...
如果它是3的倍数,ping
如果它是5的倍数,pong
否则,打印数字。
If it was multiple of 3, "ping"
If it was multiple of 5, "pong"
Else, print the number.
如果它是3和5的倍数(如15),则应打印ping和pong。
If it was multiple of 3 AND 5 (like 15), it should print "ping" and "pong".
我选择了Javascript,并想出了这个:
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,我对我非常不满意解决方案,但我无法找到更好的解决方案。
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...
推荐答案
你的解决方案非常令人满意恕我直言。很难,因为半数不是3或5的倍数,我会从另一个方向开始:
Your solution is quite satisfactory IMHO. Tough, as half numbers are not multiple of 3 nor 5, I'd start the other way around:
for (var x=1; x <= 100; x++){
if( x % 3 && x % 5 ) {
document.write(x);
} else {
if( x % 3 == 0 ) {
document.write("ping");
}
if( x % 5 == 0 ) {
document.write("pong");
}
}
document.write('<br>'); //line breaks to enhance output readability
}
此外,请注意<$ c以外的任何数字$ c> 0 和 NaN
是真值,所以我删除了不必要的!= 0
和一些括号。
Also, note that any number other than 0
and NaN
are truthy values, so I've removed the unnecessary != 0
and some pairs of parenthesis.
这是另一个版本,它不会使模数运算两次但是需要存储变量:
Here's another version, it doesn't make the same modulus operation twice but needs to store a variable:
for (var x=1; x <= 100; x++) {
var skip = 0;
if (x % 3 == 0) {
document.write('ping');
skip = 1;
}
if (x % 5 == 0) {
document.write('pong');
skip = 1;
}
if (!skip) {
document.write(x);
}
document.write('<br>'); //line breaks to enhance output readability
}
这篇关于从1到100,打印“ping”如果是3,“pong”的倍数。如果是5的倍数,或者打印数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!