4 ms·
Is the correct and most efficient way to solve it? #include <iostream> using namespace std; int main() { for (int i = 1; i <= 100; i++) {
by 50 8y ago
Is the correct and most efficient way to solve it?
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 100; i++)
{
if ((i % 3 == 0) && (i % 5 == 0)) cout << "FizzBuzz" << endl;
else if (i % 3 == 0) cout << "Fizz" << endl;
else if (i % 5 == 0) cout << "Buzz" << endl;
else cout << i << endl;
}
}
- 0xffff2 8y agoOff the top of my head, you can do a single mod 15 for the first case. I'm sure there are other micro optimizations, but really being able to write exactly what you did is sufficient to move on to real questions that actually have something to do with the job you're interviewing for.
- Metricon 8y agoTechnically, this would be more efficient: #include <iostream> using namespace std; int main() { for (int i = 1; i <= 100; i++) { bool t = (i % 3 == 0); bool f = (i % 5 == 0); if (!t && !f) { cout << i << endl; continue; } if (t) cout << "Fizz"; if (f) cout << "Buzz"; cout << endl; } } But most interviewers are interested in the basic logic of the process.