Java 实例 使用按位 XOR 运算符交换两个数字

这个 java 程序使用按位 XOR 运算符交换两个数字。在通过程序之前,让我们看看什么是按位 XOR 运算符:按位 XOR 比较两个操作数的相应位,如果它们相等则返回 1,如果它们不相等则返回 0。例如:

num1 = 11; /* equal to 00001011*/
num2 = 22; /* equal to 00010110 */

num1 ^ num2比较num1num2的相应位,如果它们不相等则生成 1,否则返回 0.在我们的例子中它将返回 29,相当于 00011101

让我们在Java 程序中写一下:

示例:使用按位运算符交换两个数字

import java.util.Scanner;
public class JavaExample 
{
    public static void main(String args[])
    {
        int num1, num2;
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter first number:");
        num1 = scanner.nextInt();
        System.out.print("Enter second number:");
        num2 = scanner.nextInt();
        /* To make you understand, lets assume I am going
         * to enter value of first number as 10 and second 
         * as 5\. Binary equivalent of 10 is 1010 and 5 is
         * 0101
         */

        //num1 becomes 1111 = 15
        num1 = num1 ^ num2;
        //num2 becomes 1010 = 10
        num2 = num1 ^ num2;
        //num1 becomes 0101 = 5
        num1 = num1 ^ num2;
        scanner.close();
        System.out.println("The First number after swapping:"+num1);
        System.out.println("The Second number after swapping:"+num2);
    }
}

输出:

Enter first number:10
Enter second number:5
The First number after swapping:5
The Second number after swapping:10
赞(0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

Java 实例