Interview Question
Country: India
Interview Type: Written Test
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
#include<math.h>
using namespace std;
int main()
{
char s[5],d[5];
int pos=0,k=0,flag=0,n,m;
cin>>s;//enter number as string
n=atoi(s);//converting string to integer leaving the decimal part
for(int i=0;i<strlen(s);i++)//loop to extract the decimal part
{
if(s[i]=='.' && flag!=1)
{pos=i;flag=1;}
else if(flag==1)
{
if(s[i]!='.')
d[k++]=s[i];
else
{cout<<"\nwrong input"<<endl;return(0);}
}
}
//n is the integer part of string s and m is the integer part of d(the decimal nos)
if(flag==1)
{m=atoi(d);}
else
m=0;
int x=n,rem,ans[100],u=0;
while(x!=0)//converting int part to binary
{rem=x%2;
x=x/2;
ans[u++]=rem;
}
for(int i=u-1;i>=0;i--)
cout<<ans[i];
if(m!=0)
{
cout<<".";
float p,q,t;
q=m/pow(10,strlen(d));//converting decimal part as float
p=q;
while(p!=0)//converting decimal part to binary
{
p=p*2;
t=int(p);
p=p-t;
cout<<t;
}
}
getch();
return(0);
}
Writing jus the algorithm
- Shivaprasad May 13, 2012