Advertisement
Josif_tepe

Untitled

Mar 3rd, 2022
1,280
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.78 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4. #include <algorithm>
  5. using namespace std;
  6. int from_binary_to_decimal(string s) {
  7.     int power_of_two = 1;
  8.     int sum = 0;
  9.     for(int i = s.size() - 1; i >= 0; i--) {
  10.         if(s[i] == '1') {
  11.             sum += power_of_two;
  12.         }
  13.         power_of_two *= 2;
  14.     }
  15.     return sum;
  16. }
  17. string from_decimal_to_binary(int x) {
  18.     string s = "";
  19.     while(x > 0) {
  20.         s += (x % 2)  + '0';
  21.         x /= 2;
  22.     }
  23.     reverse(s.begin(), s.end());
  24.     return s;
  25. }
  26. int main()
  27. {
  28.     ios_base::sync_with_stdio(false);
  29.     cout.tie(0);
  30.     cin.tie(0);
  31.     cout << from_binary_to_decimal("101") << " " << from_binary_to_decimal("1") << endl;
  32.     cout << from_decimal_to_binary(5) << endl;
  33.     return 0;
  34.  
  35. }
  36.  
  37.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement