This post is completed by 5 users
|
Add to List |
531. Convert a Decimal number to its binary representation
Given a decimal number, convert that number to its binary representation.
Example:
Number: 5, binary representation: 101 Number: 8, binary representation: 1000 Number: 105, binary representation: 1101001
Solution:
Initialize a result string and while the given number is greater than 0, keep dividing it by 2 and append the remainder of division to the result string. Once the number is 0, reverse the result string and this will be the binary representation of the given number.
Output:
Number: 5, binary representation: 101 Number: 8, binary representation: 1000 Number: 105, binary representation: 1101001