Learn-dsa..in 30 days!



























CC-4 : Convert decimal number to binary.

Description:

Given an input number, convert it into its binary form.

Test cases and expected outputs:

Input Parameters Expected outputs
Decimal num: 3 Binary num: 11
Decimal num: 9 Binary num: 1001

Pseudocode:

DecimalToBinary(num):

The number to be converted to binary is received as input parameter.
If num==0, return 0; (base case).
Recursively call decimalToBinary() with num/2 as parameter and set return value to variable retBin.
Combine binary number calaculated so far as following:
binaryNum=num %2 + 10*retBin.
Return binaryNum.

Code:

private int decimalToBinary(int num){
	if (num == 0) {
		return 0;
	}
	int retBin=decimalToBinary(num/2);
	int binaryNum=num%2 + 10*retBin;
	return binaryNum;
}

Click here to download and run code and test cases !