Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //http://pastebin.com/u/TheWhiteFang#_=_
- //yeo punya
- //Tutorial 4 section b dectobin
- #include <iostream>
- #include <string>
- using namespace std;
- string DecToBin(int);
- string OnesComp(string);
- string AddBin(string, string);
- int _tmain(int argc, _TCHAR* argv[])
- {
- int input;
- cout << "Enter a number: ";
- cin >> input;
- string out = DecToBin (input);
- cout << out << endl;
- string out1comp = OnesComp(out);
- cout << out1comp << endl;
- string add = AddBin(out, out1comp);
- cout << add << endl;
- return 0;
- }
- string DecToBin(int dec)
- {
- int remain=0;
- if(dec == 0)
- return "0";
- if(dec == 1)
- return "1";
- if (dec%2 == 0)
- return DecToBin (dec/2) + "0";
- else
- return DecToBin (dec/2) + "1";
- }
- string OnesComp(string bin){
- int len = bin.length();
- string temp;
- for (int i = 0; i < len; i++){
- if (bin[i] == '1')
- temp = temp + "0";
- else
- temp = temp + "1";
- }
- return temp;
- }
- string AddBin(string a, string b){
- string temp;
- if (a.length() == b.length()){
- for (int i = a.length()-1; i >= 0; i--){
- int tem = a[i] + b[i];
- if (tem > 97){
- temp[i] = '0';
- temp[i--] = '1';
- }
- else if (tem == 97)
- temp[i] = '1';
- else
- temp[i] = '0';
- }
- }
- return temp;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement