Skip to content

Commit 3b28ad9

Browse files
Merge pull request #64 from AayushBangroo/master
Print Binary of number using Bit Manip
2 parents 0e8912f + 141aef3 commit 3b28ad9

1 file changed

Lines changed: 47 additions & 0 deletions

File tree

Bit Manipulation/PrintBinary.java

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/*
2+
Given a number print its Binary Representation using Bit Manipulation
3+
Examples:
4+
5+
Input: 2
6+
Output: 10
7+
8+
Input: 64
9+
Output: 1000000
10+
*/
11+
12+
import java.util.Scanner;
13+
14+
public class PrintBinary {
15+
16+
public static void main(String[] args) {
17+
18+
Scanner sc = new Scanner(System.in);
19+
20+
int num = sc.nextInt();
21+
22+
printBinary(num);
23+
}
24+
25+
public static void printBinary(int num) {
26+
27+
if (num == 0) {
28+
System.out.print(0);
29+
return;
30+
}
31+
32+
//Number of bits needed to represent a number in Binary
33+
int bits = (int) (Math.log(num) / Math.log(2)) + 1;
34+
35+
for (int i = bits - 1; i >= 0; --i) {
36+
//ith bit is set
37+
if ((num & (1 << i)) != 0) {
38+
System.out.print("1");
39+
}
40+
//ith bit is not set
41+
else {
42+
System.out.print("0");
43+
}
44+
}
45+
}
46+
}
47+

0 commit comments

Comments
 (0)