Decimal to Binary

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.

Complete Code:

Output:

Number: 5, binary representation: 101
Number: 8, binary representation: 1000
Number: 105, binary representation: 1101001

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.