Advertisement
TheWhiteFang

Tutorial 4 Section B [DecToBin]

Nov 16th, 2014
259
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.54 KB | None | 0 0
  1. //http://pastebin.com/u/TheWhiteFang
  2. //Tutorial 4 Section B
  3. //credits to sasi :P
  4. #include <iostream>
  5. #include <string>
  6.  
  7. using namespace std;
  8.  
  9.  
  10. string DecToBin(int num){
  11.  
  12.  
  13.     if(num==0) return "0"; //recursive call
  14.     if(num==1) return "1";
  15.  
  16.     if(num %2 == 0) //rec base
  17.         return DecToBin(num /2) + "0";
  18.  
  19.     else
  20.         return DecToBin(num/2) + "1";
  21. }
  22.  
  23. int main(){
  24.  
  25.  
  26.     int num = 0;
  27.     cout <<"Enter any positive integer number ";
  28.     cin >> num;
  29.     string ans = DecToBin(num);
  30.     cout << "Binary of " << num << "is: " << ans <<endl;
  31.  
  32.     return 0;
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement