使用 【^ 亦或运算符】 实现【变量值交换】和 【数组反转】
废话不多说,直接上代码,一切尽在注释中!!!
废话不多说,直接上代码,一切尽在注释中!!!
package demo
;
public class XOR {
public static void main(String
[] args
) {
changeNumber(1, 2);
int[] arrOne
= { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int[] arrTwo
= { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int[] arrThree
= { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int[] arrFour
= { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
methodOne(arrOne
);
methodTwo(arrTwo
);
methodTwoSimpleFirst(arrThree
);
methodTwoSimpleSecond(arrFour
);
}
public static void changeNumber(int x
, int y
) {
x
= x
^ y
;
y
= x
^ y
;
x
= x
^ y
;
System
.out
.println("参数一的值已经更换为:" + x
);
System
.out
.println("参数二的值已经更换为:" + y
);
}
public static void methodOne(int[] arr
) {
for (int i
= 0; i
< arr
.length
/ 2; i
++) {
int temp
= arr
[i
];
arr
[i
] = arr
[arr
.length
- 1 - i
];
arr
[arr
.length
- 1 - i
] = temp
;
}
echoArr(arr
);
}
public static void methodTwo(int[] arr
) {
for (int i
= 0; i
< arr
.length
/ 2; i
++) {
int x
= arr
[i
];
int y
= arr
[arr
.length
- 1 - i
];
int z
= x
^ y
;
x
= x
^ z
;
y
= y
^ z
;
arr
[i
] = x
;
arr
[arr
.length
- 1 - i
] = y
;
}
echoArr(arr
);
}
public static void methodTwoSimpleFirst(int[] arr
) {
for (int i
= 0; i
< arr
.length
/ 2; i
++) {
int x
= arr
[i
];
int y
= arr
[arr
.length
- 1 - i
];
x
= x
^ y
;
y
= x
^ y
;
x
= x
^ y
;
arr
[i
] = x
;
arr
[arr
.length
- 1 - i
] = y
;
}
echoArr(arr
);
}
public static void methodTwoSimpleSecond(int[] arr
) {
for (int i
= 0; i
< arr
.length
/ 2; i
++) {
arr
[i
] = arr
[i
] ^ arr
[arr
.length
- 1 - i
];
arr
[arr
.length
- 1 - i
] = arr
[i
] ^ arr
[arr
.length
- 1 - i
];
arr
[i
] = arr
[i
] ^ arr
[arr
.length
- 1 - i
];
}
echoArr(arr
);
}
public static void echoArr(int[] arr
) {
for (int i
= 0; i
< arr
.length
; i
++) {
System
.out
.print(arr
[i
] + " ");
}
System
.out
.println();
}
}
附本机执行结果如下:
参数一的值已经更换为:2 参数二的值已经更换为:1 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
转载请注明原文地址:https://ipadbbs.8miu.com/read-24815.html