Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
335 views
in Technique[技术] by (71.8m points)

javascript - 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:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
}?

Fiddle

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
}

Fiddle


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...