Ber*_*ano 10 javascript fizzbuzz challenge-response
我刚从求职面试回家,面试官让我写一个程序:
它应该从1到100,并打印...
如果它是3的倍数,"ping"
如果它是5的倍数,"pong"
Else,打印数字.
如果它是3和5的倍数(如15),它应该打印"ping"和"pong".
我选择了Javascript,并想出了这个:
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)
}
}
Run Code Online (Sandbox Code Playgroud)
实际上,我对我的解决方案非常不满意,但我无法找到更好的解决方案.
有谁知道更好的方法吗?它检查了两次,我不喜欢它.我在家里做了一些测试,没有成功,这是唯一一个返回正确答案的测试......
Fab*_*tté 20
你的解决方案是相当令人满 很难,因为半数不是3和5的倍数,我会从另一个方向开始:
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
}?
Run Code Online (Sandbox Code Playgroud)
另外,请注意除了0和之外的任何数字NaN都是真值,所以我删除了不必要的!= 0和一些括号.
这是另一个版本,它不会进行两次相同的模数运算,但需要存储一个变量:
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
}
Run Code Online (Sandbox Code Playgroud)
这是我的单行:
for(var x=1;x<101;x++)document.write((((x%3?'':'ping')+(x%5?'':'pong'))||x)+'<br>');
Run Code Online (Sandbox Code Playgroud)
我正在使用三元运算符返回空字符串,或者'ping'/'pong'连接这些运算符的结果,然后执行OR(如果数字不能被3或5整除,则连接的结果''是javascript中的FALSEY) .当两种情况都为真时,连接的结果是'pingpong'.
所以基本上归结为
'' || x // returns x
'ping' || x // returns 'ping'
'pong' || x // returns 'pong'
'pingpong' || x // returns 'pingpong'
Run Code Online (Sandbox Code Playgroud)
我想出的最好的解决方案是:
for (var i = 1; i <= 100; i++) {
var message = '';
if (i%3 === 0) message += 'ping';
if (i%5 === 0) message += 'pong';
console.log(message || i);
}
Run Code Online (Sandbox Code Playgroud)