How would you iterate over the following series in Javascript/jQuery:
1, -2, 3, -4, 5, -6, 7, -8, ...
Here is how I do this:
n = 1
while (...) {
n = ((n % 2 == 0) ? 1 : -1) * (Math.abs(n) + 1);
}
Is there开发者_开发问答 a simpler method ?
You could keep two variables:
for (var n = 1, s = 1; ...; ++n, s = -s)
alert(n * s);
This is simpler
x = 1;
while (...) {
use(x);
x = - x - x / Math.abs(x);
}
or
x = 1;
while (...) {
use(x);
x = - (x + (x > 0)*2 - 1);
}
or the much simpler (if you don't need to really "increment" a variable but just to use the value)
for (x=1; x<n; x++)
use((x & 1) ? x : -x);
That looks about right, not much simpler than that. Though you could use n < 0
if you are starting with n = 1
instead of n % 2 == 0
which is a slower operation generally.
Otherwise, you will need two variables.
How about:
var n = 1;
while(...)
n = n < 0 ? -(n - 1) : -(n + 1);
You could always just use the following method:
for (var i = 1; i < 8; i++) {
var isOdd = (i % 2 === 1);
var j = (isOdd - !isOdd) * i;
}
Which is similar, by the way, to how you'd get the sign (a tri-state of -1, 0 or 1) of a number in JavaScript:
var sign = (num > 0) - (num < 0)
for (var n = 1; Math.abs(n) < 10; (n ^= -1) > 0 && (n += 2))
console.log (n);
How about some Bit Manipulation -
n = 1;
while(...)
{
if(n&1)
cout<<n<<",";
else
cout<<~n+1<<",";
}
Nothing beats the bits !!
How about:
while (...)
{
if (n * -1 > 0) { n -= 1; }
else { n += 1; }
n *= -1;
}
seems to be the simplest way.
精彩评论