L7: Operators-II

Q1. Write a program to check whether a given number is even or odd using bitwise AND operation.

import java.util.Scanner;
class Test {
  public static void main(String[] args) {
    Scanner ip=new Scanner(System.in);
    System.out.print("Enter a number: ");
    int num=ip.nextInt();
    System.out.print("Even: ");
    System.out.println((num & 1)==0 );
    }
 }

Q2. Write a program to swap two numbers utilizing bitwise XOR operation and without using a temporary variable.

import java.util.Scanner;
class Test {
  public static void main(String[] args) {
    Scanner ip=new Scanner(System.in);
    System.out.print("Enter two numbers: ");
    int n1=ip.nextInt();
    int n2=ip.nextInt();
    System.out.println("Before swapping: "+ n1+ " "+ n2);
    n1=n1^n2;
    n2=n1^n2;
    n1=n1^n2;
    System.out.println("After Swapping: "+ n1+ " "+ n2);
    }
 }

Q3. Write a program to check whether a given number is power of 2 using bitwise operations.

import java.util.Scanner;
class Test {
  public static void main(String[] args) {
    Scanner ip=new Scanner(System.in);
    System.out.print("Enter a number: ");
    int num=ip.nextInt();
    System.out.print("Power of 2: ");
    System.out.println((num&num-1)==0);
    }
 }

Q4. Write a program to determine whether a number is sparse or not. A number is sparse if it does not have adjacent 1s in its binary representation.

import java.util.Scanner;
class Test {
  public static void main(String[] args) {
    Scanner ip=new Scanner(System.in);
    System.out.print("Enter a number: ");
    int num=ip.nextInt();
    System.out.print("Sparse number: ");
    System.out.println((num&num<<1)==0);
    }
  }