Bitwise Operators Demo

easy Programming Basics

Problem

Two non-negative integers a and b are given. Print six lines: and=a&b, or=a|b, xor=a^b, not-a=~a, a-shift-left=a<<1 and a-shift-right=a>>1.

Constraints

  • 0 <= a, b <= 10^9

Examples

Input

12 10

Output

and=8
or=14
xor=6
not-a=-13
a-shift-left=24
a-shift-right=6

Solutions

Best approachTime O(1)Space O(1)

Bitwise operators work on the binary form of numbers. Shifting left by one doubles a number and shifting right by one halves it. The inputs stay below 2^31 so that Java, JavaScript and Python give the same answers.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Bitwise results.
 * Input   : Two integers.
 * Output  : Six lines.
 * Approach: Use the operators.
 * Time    : O(1)
 * Space   : O(1)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static String[] solve(long a, long b) {
        // Step 1: Each operator works on the bits of the numbers.
        // & keeps a bit only when both numbers have it. | keeps it when one of them has it.
        // ^ keeps it when exactly one of them has it.
        // Step 2: ~a flips every bit, so the result is -a - 1. << 1 doubles the number, >> 1 halves it (rounded down).
        return new String[] {
            "and=" + (a & b),
            "or=" + (a | b),
            "xor=" + (a ^ b),
            "not-a=" + (~a),
            "a-shift-left=" + (a << 1),
            "a-shift-right=" + (a >> 1)
        };
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        long a = scanner.nextLong();
        long b = scanner.nextLong();
        System.out.println(String.join("\n", solve(a, b)));
    }
}
Hints (1)
  1. What is ~5?