Bloomberg LP Interview Question
Financial Software DevelopersCountry: United States
Interview Type: In-Person
#include <iostream>
#include <deque>
using namespace std;
void main()
{
int d(0);
deque<char> binary;
cout<<"Please Enter Decimal Number:"<<endl;
cin >> d;
while(d > 0)
{
if(d%2==0)
{
binary.push_front('0');
}
else
{
binary.push_front('1');
}
d = d/2;
}
for (deque<char>::iterator it = binary.begin(); it!=binary.end(); ++it){
cout << *it;
}
cout<<endl;
}
Could somebody help me finish the negative part?
public class Convert {
public static String convert(double num) {
if (num >= 0) {
String n = String.valueOf(num);
int int_rep = Integer.parseInt(n.substring(0, n.indexOf(".")));
double dec_rep = Double.parseDouble(n.substring(n.indexOf(".")));
StringBuilder sb_int = new StringBuilder();
while (int_rep > 0) {
sb_int.append(int_rep % 2);
int_rep /= 2;
}
StringBuilder sb_rep = new StringBuilder();
while (dec_rep > 0) {
if (sb_rep.length() > 32) {
return "Error";
}
if (dec_rep == 1) {
sb_rep.append(1);
break;
}
double r = dec_rep * 2;
if (r >= 1) {
sb_rep.append(1);
dec_rep = r - 1;
} else {
sb_rep.append(0);
dec_rep = r;
}
}
String tail = sb_rep.toString().equals("") ? "0" : sb_rep.toString();
return sb_int.reverse().toString() + "." + tail;
} else {
//negative
}
return null;
}
public static void main(String[] args) {
System.out.println(Double.MAX_VALUE);
System.out.println(convert(3));
}
}
A simple solution is quoted below from umich.edu site
#include <iostream.h>
void binary(int);
void main(void) {
int number;
cout << "Please enter a positive integer: ";
cin >> number;
if (number < 0)
cout << "That is not a positive integer.\n";
else {
cout << number << " converted to binary is: ";
binary(number);
cout << endl;
}
}
void binary(int number) {
int remainder;
if(number <= 1) {
cout << number;
return;
}
remainder = number%2;
binary(number >> 1);
cout << remainder;
}
--------------------------------------------------------------------------------
Sample Run
Please enter a positive integer value: 24
24 converted to binary is: 11000
This program prompts the user for a positive integer. The function binary divides the integer by 2 (using the bitshift operation) until the number becomes 1, at which point it outputs 1 and steps back thru the function calls outputting the remainder from previous divisions. This program has been tested and works for all integers within C++ limits.
int decimal,index=0;
- tosha shah March 22, 2012char *binary;
printf("Enter a decimal number:");
scanf("%d",&decimal);
printf("The binary is ");
binary = (char* )malloc(sizeof(char)*10);
while(decimal > 0)
{
//binary[index] = (int)malloc(sizeof(int));
if(decimal%2==0)
{
binary[index] = '0';
}
else
{
binary[index] = '1';
}
printf("%d",decimal%2);
decimal = decimal/2;
index++;
}
binary[index]='\0';
printf("The reverse of binary is: %s",strrev(binary));