问题
lets say you want to make a program that will print the numbers 1-9 over and over again
123456789123456789123456789
i guess the most obvious way to do it would be to use a loop
int number = 1;
while(true)
{
print(number);
number = number + 1;
if(number > 9)
number = 1;
}
before i go any further, is this the best way to do this or is there a more common way of doing this?
回答1:
The most obvious way would be this:
for (;;)
{
for (int i = 1; i < 10; ++i)
{
print(i);
}
}
Why you'd want to optifuscate it is beyond me. Output is going to so overwhelm the computation that any kind of optimization is irrelevant.
回答2:
Will this do?
while(true)
{
print("123456789");
}
回答3:
First off, why are you trying to "optimize" this? Are you optimizing for speed? Space? Readability or maintainability?
A "shorter" way to do this would be like so:
for (int i = 1; true; i++)
{
print(i);
i = (i + 1) % 10;
}
All I did was:
- Convert the while loop to a for loop
- Convert increment + conditional to increment + mod operation.
This really is a case of micro-optimization.
回答4:
My answer is based off Mike's answer but with further optimization:
for (int i = 1; true; i++)
{
std::cout << ('0' + i);
i = (i + 1) % 10;
}
Printing a number is way more expansive then printing a char and addition.
回答5:
Everyone using the %
operator so far seems to be under the impression that ten values are involved. They also overlook the fact that their logic will sometimes generate 0
. One way to do what you want is:
int i = 1;
while (true) {
print(i);
i = (i % 9) + 1;
}
来源:https://stackoverflow.com/questions/5767916/print-a-series-of-numbers-optimization-part-1