This post is completed by 5 users

  • 1
Add to List
Beginner

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.




public class Main { public static void toBinary(int num){ StringBuilder sb = new StringBuilder(); int n = num; while(num>0){ sb.append(num%2); num /= 2; } System.out.println("Number: "+ n + ", binary representation: " + sb.reverse().toString()); } public static void main(String[] args) { toBinary(5); toBinary(8); toBinary(105); } }



def to_binary(num): binary_str = '' n = num while num > 0: binary_str += str(num % 2) num //= 2 binary_str = binary_str[::-1] # Reverse the binary string print(f"Number: {n}, binary representation: {binary_str}") to_binary(5) to_binary(8) to_binary(105)



package main import ( "fmt" "strconv" ) func toBinary(num int) { binaryStr := "" n := num for num > 0 { binaryStr = strconv.Itoa(num%2) + binaryStr num /= 2 } fmt.Printf("Number: %d, binary representation: %s", n, binaryStr) fmt.Println("") } func main() { toBinary(5) toBinary(8) toBinary(105) }

Output:

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