Bit Manipulation
Completed
For each input integer print: its binary form, the number of set bits (Integer.bitCount), whether it is a power of two (n > 0 && (n & (n - 1)) == 0), and n << 1 and n >> 1.
Input
n, then n non-negative integers.
Output
n lines.
Example
Input
4 5 8 0 255
Output
101 2 false 10 2 1000 1 true 16 4 0 0 false 0 0 11111111 8 false 510 127
Editor
Java
Hints
x & (x - 1) clears the lowest set bit.
<< multiplies by 2, >> divides by 2.
Solution explanation
Bitwise operators work directly on the binary representation - used in flags, hashing and fast arithmetic.
Show solution
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
int x = sc.nextInt();
boolean pow2 = x > 0 && (x & (x - 1)) == 0;
System.out.println(Integer.toBinaryString(x) + " " + Integer.bitCount(x) + " " + pow2 + " "
+ (x << 1) + " " + (x >> 1));
}
}
}