Sponsored Links
Ad by Google
Java programming interview question, specially for freshers, to check the candidates logical analysis and basic knowledge of coding. Some of the popular coding interview questions like how to balanced parentheses and finding second largest numbers from an array. In this post, I'm going to show you a simple Java code to convert decimal to binary.
Converting decimal to binary in Java
OUTPUT:
Binary form of 140 is = 10001100
Binary form of 140 is = 10001100
Converting decimal to binary in Java
- Using built in function called as toBinaryString() and
- Your own calculation to compute binary.
package com.javamakeuse.poc; /** * * @author javamakeuse * */ public class DecimalToBinary { // converting decimal to binary using toBinaryString() public static void convertDecimalToBinary(int num) { System.out.println("Binary form of " + num + " is = " + Integer.toBinaryString(num)); } // converting decimal to binary via calculating reminder values public static void convertDecimalToBinary2(int num) { if (num == 0) { System.out.println(0); } else { String binaryString = ""; int n = num; while (n > 0) { int reminder = n % 2; binaryString = reminder + binaryString; n = n / 2; } System.out.println("Binary form of " + num + " is = " + binaryString); } } public static void main(String[] args) { // calling methods convertDecimalToBinary(140); convertDecimalToBinary2(140); } }
OUTPUT:
Binary form of 140 is = 10001100
Binary form of 140 is = 10001100
Sponsored Links
0 comments:
Post a Comment