0% found this document useful (0 votes)
20 views2 pages

Bit Manipulation Solutions

Uploaded by

vishalsingh36061
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views2 pages

Bit Manipulation Solutions

Uploaded by

vishalsingh36061
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

BIT MANIPULATION SOLUTIONS

[email protected]
Solution 1: The value of x^x = 0.
Think about it, xor gives 0 when the bits are the same. If we compare the same number to
itself, the bits will always be the same. So, the answer of x^x will always be 0.

Solution 2: The idea is to use XOR operators to swap two numbers by their property
x^x=0
public class Solution {
public static void main(String[] args) {
int x = 3, y = 4;
System.out.println("Before swap: x = " + x + " and y = " + y);
//swap using xor
x = x ^ y;
y = x ^ y;
x = x ^ y;
System.out.println("After swap: x = " + x + " and y = " + y);
}
}

Solution 3 : The expression -~x will add 1 to an integer x. We know that to get negative of
a number, invert its bits and add 1 to it (Remember negative numbers are stored in 2’s
complement form), i.e.,

-x = ~x + 1;
-~x = x + 1 (by replacing x by ~x)

public class Solution {


public static void main(String[] args) {
int x = 6;
System.out.println(x + " + " + 1 + " is " + -~x);
x = -4;
System.out.println(x + " + " + 1 + " is " + -~x);
x = 0;
System.out.println(x + " + " + 1 + " is " + -~x);
}
}
[email protected]
Solution 4 :
public class Solution {
public static void main(String[] args) {
// Convert uppercase character to lowercase
for (char ch = 'A'; ch <= 'Z'; ch++) {
System.out.println((char)(ch | ' '));
// prints abcdefghijklmnopqrstuvwxyz
}
}
}

You might also like