fizzbuzz - C / C++ Interview: Code Optimization -
i had interview today. question optimize code below. if see code below after loop there 4 steps of "if-else" follows. so, interviewer asked me optimize 3 if-else line. have tried lot. not able find solution. told me if know scripting language then, can use them also. please me in optimizing same.
int main() { int = 1; for(i; <= 100; i++) { if((i % 3 == 0 && % 5 == 0)) {cout << "pr\n";} else if(i % 3 == 0) {cout << "p\n";} else if(i % 5 == 0) {cout << "r\n";} else {cout << <<"\n";} } system("pause"); return 0; }
this known question... "fizzbuzz".
you can solve without explicit ifs
const char *messages[] = {"%i\n", "p\n", "r\n", "pr\n"}; (i=1; i<=100; i++) { printf(messages[((i % 3)==0) + 2*((i % 5)==0))], i); }
Comments
Post a Comment