While working on this puzzle, became confused, but this can be simplified if we first write the state diagram and then the code. The state diagram should consider odd/even and +ve/-ve numbers.
A simple control flow can be as follows:
A: 1 → 2
B: 2 → -1
C: -1 → -2
D: -2 → 1
E: 1 → 2
Notice that E and A are same.
Once we have this,
if n is +ve: if n is odd : return n+1 if n is even : return -1* (n-1) else if n is -ve: if n is odd : return n-1 if n is even : return -1 * (n+1)
We get the highest rated solution on stackoverflow.
No comments:
Post a Comment