#include <iostream> using namespace std; int main() { int a[10], n, i; cout<<"Enter the number to convert: "; cin>>n; for(i=0; n>0; i++) { a[i]=n%2; n= n/2; } cout<<"Binary of the given number= "; for(i=i-1 ;i>=0 ;i--) { cout<<a[i]; } return 0; }
不考虑算法实现,我们的思路是什么?
除二倒序取余
算法想实现倒序,那么就可以用栈
stack<int> dec2bin(int num) { stack<int> bin; while (num != 0) { bin.push(num % 2); // 取余并压栈 num /= 2; // 向下取整 } return bin; } int main() { int a = 9; stack<int> stk = dec2bin(a); int len = stk.size(); for (int i = 0; i < len; i++) { int b = stk.top(); cout << b; stk.pop(); } }