如何使用按位运算符更改 int 的符号?显然我们可以使用x*=-1
or x/=-1
。有没有最快的方法来做到这一点?
我做了一个小测试,如下所示。只是为了好奇...
public class ChangeSign {
public static void main(String[] args) {
int x = 198347;
int LOOP = 1000000;
int y;
long start = System.nanoTime();
for (int i = 0; i < LOOP; i++) {
y = (~x) + 1;
}
long mid1 = System.nanoTime();
for (int i = 0; i < LOOP; i++) {
y = -x;
}
long mid2 = System.nanoTime();
for (int i = 0; i < LOOP; i++) {
y = x * -1;
}
long mid3 = System.nanoTime();
for (int i = 0; i < LOOP; i++) {
y = x / -1;
}
long end = System.nanoTime();
System.out.println(mid1 - start);
System.out.println(mid2 - mid1);
System.out.println(mid3 - mid2);
System.out.println(end - mid3);
}
}
输出几乎类似于:
2200211
835772
1255797
4651923