-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDecimalToBinary.java
More file actions
57 lines (49 loc) · 1.15 KB
/
DecimalToBinary.java
File metadata and controls
57 lines (49 loc) · 1.15 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
import java.lang.*;
import java.io.*;
import java.util.*;
class DecimalToBinary{
static long decimal, binary, c, a, b;
static String result=" ";
Scanner sc=new Scanner(System.in);
void doAll(){
System.out.println("This application converts a decimal number to binary");
try{
System.out.println("Enter the decimal number:");
decimal=sc.nextLong();
}
catch(InputMismatchException ime){
System.out.println("Invalid Input, Please try again");
System.exit(0);
}
if (decimal==1){
System.out.println("\n1");
System.exit(0);
}
else if(decimal==0){
System.out.println("\n0");
System.exit(0);
}
for(a=0; a<=2147483647; a++){
if((decimal!=0)&&(decimal!=1)){
c=decimal%2;
decimal=decimal/2;
result= result.concat(Long.toString(c));
}
else if(decimal==1){
decimal=0;
result= result.concat("1");
}
else if(decimal<=0){
StringBuilder ans = new StringBuilder();
ans.append(result);
ans.reverse();
System.out.println("\n\n\n"+ans);
System.exit(0);
}
}
}
public static void main(String[] args){
DecimalToBinary binary=new DecimalToBinary();
binary.doAll();
}
}