forked from ritikkhatana79020/Hacktoberfest2020
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuestion_4.java
More file actions
115 lines (99 loc) · 1.72 KB
/
Question_4.java
File metadata and controls
115 lines (99 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
/*Q4. Write the function transforming a decimal number into a binary number by using stack*/
package questions;
import java.util.*;
class Node
{
Node next;
int data;
public Node()
{
this.next = null;
this.data = 0;
}
void set_Data(int data)
{
this .data = data;
}
void set_Link(Node next)
{
this.next = next;
}
int get_Data()
{
return data;
}
Node get_Link()
{
return next;
}
}
class Stack_Implement
{
Node top = null;
void push(int data)
{
Node node = new Node();
if(top==null)
{
top = node;
node.set_Data(data);
}
else
{
node.set_Link(top);
node.set_Data(data);
top = node;
}
}
int pop()
{
int element;
if(top==null)
{
System.out.println("Underflow");
element = -1;
}
else
{
element = top.get_Data();
top = top.next;
}
return element;
}
}
public class Question_4 {
String binary(int decimal)
{
String binary ="";
int size=1;
Stack_Implement stack = new Stack_Implement();
if(decimal>0)
{
while(decimal!=1)
{
int temp;
temp = decimal%2;
stack.push(temp);
decimal = decimal/2;
size++;
}
stack.push(1);
for(int i=0;i<size;i++)
{
binary = binary + Integer.toString(stack.pop());
}
}
else
{
binary = "0";
}
return binary;
}
public static void main(String... args)
{
Scanner scan = new Scanner (System.in);
Question_4 conversion = new Question_4();
System.out.println("Enter the decimal number");
System.out.print(conversion.binary(scan.nextInt()));
scan.close();}
}