-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecimalToBinary_2.java
More file actions
41 lines (32 loc) · 977 Bytes
/
decimalToBinary_2.java
File metadata and controls
41 lines (32 loc) · 977 Bytes
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
/*
# convert a decimal input to binary (another method)
steps:
-> converts using successive division method
-> a while loop, in each steps, gets remainder = decimal % 2 and makes decimal input half
-> then it positions the remainder in position by multiplying it to appropriate value
-> the result binary value is returned at the end
*/
import java.util.*;
public class Main
{
public static long makebin (int decimal)
{
long resultBin = 0;
long multiplier = 1;
int remainder;
while (decimal != 0)
{
remainder = decimal % 2;
decimal /= 2;
resultBin += remainder * multiplier;
multiplier *= 10;
}
return resultBin;
}
public static void main (String [] args)
{
Scanner sc = new Scanner (System.in);
int decimal = sc.nextInt();
System.out.println (makebin (decimal));
}
}