convert the integer number to its binary representation.
Write a program to print Binary representation of a given number N.
Example 1:
Input: N = 2 Output: 000000000000000000000000000010 Explanation: The binary representation of 2 is '10' but we need to print in 30 bits so append remaining 0's in the left.
ANSWER:
string getBinaryRep(int N)
{
vector<int> vec;
while(N>0)
{
int rem=N%2;
vec.push_back(rem);
N=N/2;
}
int l=30-vec.size();
for(int i=0;i<l;i++)
{
vec.push_back(0);
}
string s="";
for(int i=vec.size()-1;i>=0;i--)
{
if(vec[i]==1)
{
s=s+"1";
}
else
{
s=s+"0";
}
}
return s;
}
Comments
Post a Comment