Advertisement
Josif_tepe

Untitled

Jul 1st, 2025
338
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.64 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstring>
  3. using namespace std;
  4. string to_binary(int x) {
  5.     string res = "";
  6.     while(x > 0) {
  7.         int rem = x % 2;
  8.         x /= 2;
  9.         res += (rem + '0');
  10.     }
  11.     reverse(res.begin(), res.end());
  12.     return res;
  13. }
  14.  
  15. int to_decimal(string s) {
  16.     int res = 0;
  17.     int pow_of_two = 1;
  18.    
  19.     for(int i = (int) s.size() - 1; i >= 0; i--) {
  20.         if(s[i] == '1') {
  21.             res += pow_of_two;
  22.         }
  23.        
  24.         pow_of_two *= 2;
  25.     }
  26.     return res;
  27. }
  28.  
  29. int main()
  30. {
  31.     cout << to_binary(786) << endl;
  32.     cout << to_decimal("1100010010") << endl;
  33.     return 0;
  34. }
  35.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement