Problem: Given a number, write a program to convert it into binary form.
For example:
Binary representation of 25 is (11001)2
Method 1: Recursive
For example:
Input: n = 499 Output: 111110011 Input: n = 5 Output: 101 Input: n = 25 Output: 11001How to convert a decimal to binary?
Binary representation of 25 is (11001)2
Method 1: Recursive
- if num > 1
- push num on stack
- do a recursive call on 'num / 2'
- pop num from stack, divide it by 2 and print it's remainder
#include<bits/stdc++.h>
using namespace std;
void binary(int n)
{
if (n > 1)
binary(n/2);
cout<<n%2;
}
/* driver fucntion */
int main(void)
{
int num = 499;
binary(num);
cout<<"\n";
return 0;
}
Output:
111110011Method 2: iterative
#include <bits/stdc++.h>
using namespace std;
/* driver fucntion */
int main()
{
int n = 5;
string ans = "";
while(n > 0)
{
/* if reminder is 1, append to ans */
if(n%2!=0)
ans += "1";
else
ans += "0";
n/=2;
}
/* reverse the string to get required answer */
reverse(ans.begin(), ans.end());
cout<<ans<<"\n";
return 0;
}
Output:
101
