fork download
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. // 十进制转二进制
  6. void decToBin(int n) {
  7. if (n == 0) { // 单独处理0
  8. cout << 0;
  9. return;
  10. }
  11. vector<int> bits;
  12. while (n > 0) {
  13. bits.push_back(n % 2); // 保存余数
  14. n = n / 2;
  15. }
  16. // 逆序输出
  17. for (int i = bits.size() - 1; i >= 0; i--) {
  18. cout << bits[i];
  19. }
  20. }
  21.  
  22. int main() {
  23. int num;
  24. cout << "请输入一个十进制整数:";
  25. cin >> num;
  26. cout << "二进制:";
  27. decToBin(num);
  28. return 0;
  29. }
Success #stdin #stdout 0s 5316KB
stdin
12
stdout
请输入一个十进制整数:二进制:1100