Skip to content

Instantly share code, notes, and snippets.

@jamby77
Created November 8, 2017 14:20
Show Gist options
  • Save jamby77/11f19e3adb79df3f7bb6fb15ee65833e to your computer and use it in GitHub Desktop.
Save jamby77/11f19e3adb79df3f7bb6fb15ee65833e to your computer and use it in GitHub Desktop.
#include <iostream>
#include <string>
#include <math.h>
using namespace std;
string decimalToBinary(unsigned int a)
{
string b = "";
if (a == 0)
{
b = "0";
}
else if (a == 1)
{
b = "1";
}
else if (a % 2 == 0)
{
// modulo is 0, add a "0" to result
b = decimalToBinary(a / 2) + "0";
}
else
{
// modulo is 1, add a "1" to result
b = decimalToBinary(a / 2) + "1";
}
return b;
}
string convert(string binNum)
{
int s1 = 0;
int s0 = 0;
int c = binNum.size();
for(int i = 0; i < c; i++) {
if(binNum[i] == '1') {
s1++;
s0 = 0;
} else {
s0++;
s1 = 0;
}
if (s1 > 1) {
binNum[i] = (s1 % 2 == 0) ? '0' : '1';
}
if (s0 > 1) {
binNum[i] = (s0 % 2 == 0) ? '1' : '0';
}
}
return binNum;
}
int binaryToDecimal(string binNum)
{
int t, idx, i;
int d = 0;
int c = binNum.size();
for(i = 0; i < c; i++) {
idx = c-1-i;
if(binNum[idx] == '1') {
t = pow(2, i);
d += t;
}
}
return d;
}
int main()
{
unsigned int n = 60;
cout << "Enter a number less than 999 999 999" << endl;
cin >> n;
cout << binaryToDecimal(convert(decimalToBinary(n))) << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment