最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - How to iterate over the series: 1, -2, 3, -4, 5, -6, 7, -8, ...? - Stack Overflow

matteradmin12PV0评论

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 ?

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 ?

Share Improve this question asked Jun 5, 2011 at 13:10 Misha MoroshkoMisha Moroshko 172k230 gold badges520 silver badges760 bronze badges 0
Add a ment  | 

8 Answers 8

Reset to default 11

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.

Articles related to this article

Post a comment

comment list (0)

  1. No comments so far