Advertisement
TheWhiteFang

tutorial 4 section B yeo rev.

Dec 18th, 2014
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.23 KB | None | 0 0
  1. //http://pastebin.com/u/TheWhiteFang#_=_
  2. //yeo punya
  3. //Tutorial 4 section b dectobin
  4. #include <iostream>
  5. #include <string>
  6. using namespace std;
  7.  
  8. string DecToBin(int);
  9. string OnesComp(string);
  10. string AddBin(string, string);
  11.  
  12.  
  13. int _tmain(int argc, _TCHAR* argv[])
  14. {
  15.     int input;
  16.     cout << "Enter a number: ";
  17.     cin >> input;
  18.     string out = DecToBin (input);
  19.     cout << out << endl;
  20.     string out1comp = OnesComp(out);
  21.     cout << out1comp << endl;
  22.     string add = AddBin(out, out1comp);
  23.     cout << add << endl;
  24.     return 0;
  25. }
  26.  
  27. string DecToBin(int dec)
  28. {
  29.     int remain=0;
  30.     if(dec == 0)
  31.         return "0";
  32.     if(dec == 1)
  33.         return "1";
  34.     if (dec%2 == 0)
  35.         return DecToBin (dec/2) + "0";
  36.     else
  37.         return DecToBin (dec/2) + "1";
  38. }
  39. string OnesComp(string bin){
  40.     int len = bin.length();
  41.     string temp;
  42.     for (int i = 0; i < len; i++){
  43.         if (bin[i] == '1')
  44.             temp = temp + "0";
  45.         else
  46.             temp = temp + "1";
  47.     }
  48.     return temp;
  49. }
  50. string AddBin(string a, string b){
  51.     string temp;
  52.     if (a.length() == b.length()){
  53.         for (int i = a.length()-1; i >= 0; i--){
  54.             int tem = a[i] + b[i];
  55.             if (tem > 97){
  56.                 temp[i] = '0';
  57.                 temp[i--] = '1';
  58.             }
  59.             else if (tem == 97)
  60.                 temp[i] = '1';
  61.             else
  62.                 temp[i] = '0';
  63.         }
  64.  
  65.    
  66.     }
  67.     return temp;
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement