1public class DecimalToBinaryWithoutArray
2{
3 static void toBinary(int num)
4 {
5 StringBuilder sb = new StringBuilder();
6 int a = 0;
7 while(num > 0)
8 {
9 sb.append(num % 2);
10 a++;
11 num = num / 2;
12 }
13 System.out.println(sb.reverse());
14 }
15 public static void main(String[] args)
16 {
17 int number = 20;
18 toBinary(number);
19 }
20}
1public static String makeBinaryString(int n) {
2 StringBuilder sb = new StringBuilder();
3 while (n > 0) {
4 sb.append(n % 2);
5 n /= 2;
6 }
7 sb.reverse();
8 return sb.toString();
9}
1public class DecimalToBinaryExample2{
2public static void toBinary(int decimal){
3 int binary[] = new int[40];
4 int index = 0;
5 while(decimal > 0){
6 binary[index++] = decimal%2;
7 decimal = decimal/2;
8 }
9 for(int i = index-1;i >= 0;i--){
10 System.out.print(binary[i]);
11 }
12System.out.println();//new line
13}
14public static void main(String args[]){
15System.out.println("Decimal of 10 is: ");
16toBinary(10);
17System.out.println("Decimal of 21 is: ");
18toBinary(21);
19System.out.println("Decimal of 31 is: ");
20toBinary(31);
21}}
1Convert decimal to binary using toBinaryString() method
2public class DecimalToBinary
3{
4 public static void main(String[] args)
5 {
6 System.out.println("decimal to binary using toBinaryString() 104: ");
7 // to binary string java
8 System.out.println(Integer.toBinaryString(104));
9 System.out.println("\ndecimal to binary using toBinaryString() 554: ");
10 // tobinarystring
11 System.out.println(Integer.toBinaryString(554));
12 System.out.println("\ndecimal to binary using toBinaryString() 644: ");
13 System.out.println(Integer.toBinaryString(644));
14 }
15}