How to sort through the series: 1, -2, 3, -4, 5, -6, 7, -8, ...?

How would you repeat the following series in Javascript / jQuery:

1, -2, 3, -4, 5, -6, 7, -8, ...

Here is how I do it:

n = 1
while (...) {
  n = ((n % 2 == 0) ? 1 : -1) * (Math.abs(n) + 1);
}

Is there a simpler method?

+3
source share
8 answers

You can save two variables:

for (var n = 1, s = 1; ...; ++n, s = -s)
  alert(n * s);
+11
source

It is easier

x = 1;
while (...) {
    use(x);
    x = - x - x / Math.abs(x);
}

or

x = 1;
while (...) {
    use(x);
    x = - (x + (x > 0)*2 - 1);
}

or much simpler (if you do not need to "increase" the variable, but simply use the value)

for (x=1; x<n; x++)
    use((x & 1) ? x : -x);
+4
source

, . n < 0, n = 1 n % 2 == 0, .

.

+2

:

var n = 1;
while(...)
    n = n < 0 ? -(n - 1) : -(n + 1);
+2

:

for (var i = 1; i < 8; i++) {
  var isOdd = (i % 2 === 1);
  var j = (isOdd - !isOdd) * i;
}

, , , (- -1, 0 1) JavaScript:

var sign = (num > 0) - (num < 0)
0
for (var n = 1; Math.abs(n) < 10; (n ^= -1) > 0 && (n += 2))
   console.log (n);
0

How about some manipulation bits -

n = 1;
while(...)
{
    if(n&1)
    cout<<n<<",";
    else
    cout<<~n+1<<",";
}

Nothing beats bits!

0
source

What about:

while (...) 
{ 
    if (n * -1 > 0) { n -= 1; }
    else { n += 1; } 

    n *= -1;
}

It seems the easiest way.

-1
source

All Articles