十进制转换为二进制非递归栈实现
用栈实现十进制转换为二进制,用到模板库中的关于栈的部分函数。
以下是C++源代码:
#include<bits/stdc++.h>
using namespace std;
stack<int> sta;
int main(){
int n;
while(cin>>n){
while(!sta.empty()) sta.pop();
if(n<0){
cout<<"-";
n=-n;
}
if(n==0){
puts("0");
continue;
}
while(n){
if(n&1) sta.push(1);
else sta.push(0);
n>>=1;
}
while(!sta.empty()){
cout<<sta.top();
sta.pop();
}
puts("");
}
return 0;
}
现在还有许多不懂的地方,以后再做注释和修改。
还没有评论,来说两句吧...