Amazon Interview Question
SDE1sCountry: India
Interview Type: Written Test
def dec2bin(number):
## integer part:
int_number = int(number)
int_bin_str = ''
while int_number != 0:
(int_number, remainder) = divmod(int_number, 2)
int_bin_str = str(remainder) + int_bin_str
## fractional part
frac_number = number - int(number)
frac_bin_str = ''
count = 0
while( count < 4):
frac_bin_str += str(int(2.0 * frac_number))
frac_number = 2*frac_number - int(2*frac_number)
count += 1
return int_bin_str+"."+frac_bin_str
## MAIN ##
print dec2bin(10)
print dec2bin(2.22)
print dec2bin(0.876)
#include <stdio.h>
#include <string>
void dectobin(const unsigned int& num)
{
unsigned int n = num;
std::string strout;
while (0 != n) {
if ((1 & n) == 1) {
strout.insert(0, "1");
printf("1\n");
}
else {
strout.insert(0, "0");
printf("0\n");
}
n = n >> 1;
}
printf("Decimal: %u Binary: %s\n", num, strout.data());
}
int main(int argc, char* argv[])
{
int num = 120;
dectobin((unsigned int)num);
return 0;
}
#include<iostream>
#include<cmath>
using namespace std;
void binary(int n) //prints binary representation of number before decimal point
{
if(n>1)
{
binary(n/2);
}
cout<<n%2;
}
void bin_dec(double n) // prints binary representation of number after decimal point
{
for(int i=0;i<4;i++)
{
n=n*2;
if(n>=1)
{
cout<<1;
n=n-floor(n);
continue;
}
cout<<0;
}
}
int main()
{
double n,n2;
int n1;
cout<<"Enter the decimal number. \n";
cin>>n;
n1=floor(n);
binary(n1);
n2=n-n1;
cout<<".";
bin_dec(n2);
return 0;
}
Here is my implementation using Java. You could always use Integer.toBinaryString(int) to convert the number before the decimal, but I believe that would be considered cheating in the form of a test/interview. Feel free to comment.
- braaap June 22, 2013