Lte's have a look at the algorithm.
Let's take a number, say 59. Now let's convert it to Binary:
Number = 59
Let's take a number, say 59. Now let's convert it to Binary:
Number = 59
Divide:59/2
Quotient: 59
Remainder :1
Divide:29/2
Quotient: 29
Remainder :1
Divide:14/2
Quotient: 14
Remainder :0
Divide:7/2
Quotient: 7
Remainder :1
Divide:3/2
Quotient: 3
Remainder :1
Divide:1/2
Quotient: 1
Remainder :1
Binary Represenation of 59 = 111011
Now let's have a look at the code:
public class DecimalToBinary {
public static void main(String[] args) {
int num = 59;
int digit = num;
String binaryNum = "";
while(true){
System.out.println("Divide:" + digit + "/2");
System.out.println("Quotient: " + digit);
int remainder = digit%2;
System.out.println("Remainder :" + remainder);
binaryNum = String.valueOf(remainder) + binaryNum;
digit = digit/2;
if(digit<1){
break;
}
}
System.out.println("Binary Represenation of " + num + " = " + binaryNum);
}
}
No comments:
Post a Comment