-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDecimalToBinaryOctalHex.java
More file actions
53 lines (41 loc) · 1.67 KB
/
DecimalToBinaryOctalHex.java
File metadata and controls
53 lines (41 loc) · 1.67 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
// Write a program to convert decimal number to its binary, octal and hexadecimal equivalents
import java.util.Scanner;
public class DecimalToBinaryOctalHex {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a decimal number: ");
int decimal = sc.nextInt();
String binary = decimalToBase(decimal, 2);
String octal = decimalToBase(decimal, 8);
String hex = decimalToBase(decimal, 16);
System.out.println("Binary: " + binary);
System.out.println("Octal: " + octal);
System.out.println("Hexadecimal: " + hex);
}
public static String decimalToBase(int decimal, int base) {
String digits = "0123456789ABCDEF";
String result = "";
while (decimal > 0) {
int digit = decimal % base;
result = digits.charAt(digit) + result;
decimal /= base;
}
return result;
}
}
/*
import java.util.Scanner;
public class DecimalToBinaryOctalHex {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a decimal number: ");
int decimal = sc.nextInt();
String binary = Integer.toBinaryString(decimal);
String octal = Integer.toOctalString(decimal);
String hex = Integer.toHexString(decimal);
System.out.println("Binary: " + binary);
System.out.println("Octal: " + octal);
System.out.println("Hexadecimal: " + hex);
}
}
*/