I was asked in an interview : how to convert 0 to 1 and 1 to 0. I answered :
- Simple
if
andswitch
- Bit flipping.
Are there any other approach?
I was asked in an interview : how to convert 0 to 1 and 1 to 0. I answered :
if
and switch
Are there any other approach?
Simple arithmetic:
x = 1 - x;
Actually, there are an infinite number of polynomials that will map 1 to 0 and vice versa. For example:
x = x * x * x * x * x - x * x * x * x + x * x - 2 * x + 1;
I guess you could do ABS(VAR - 1) but i think your approaches are more elegant
This should work for any two numbers...
(EDIT: looking at the other answers I may have misread the question... but I still like my answer :-)
public class X
{
public static void main(final String[] argv)
{
int x = Integer.parseInt(argv[0]);
int y = Integer.parseInt(argv[1]);
x += y;
y = x - y;
x = x - y;
System.out.println(x);
System.out.println(y);
}
}
Some Trig: COS(PI * N)^2
In python
import math
math.cos(math.pi * n) ** 2
I can't believe people forgot modulus:
(3 + n) % 2
Take a paper clip. Straighten it out. It's a 1. Bend it to meet its ends. It's a 0. To make it a 1, straighten it.