File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+
You can’t perform that action at this time.
0 commit comments