十进制转换为二进制非递归栈实现

傷城~ 2022-04-03 16:27 307阅读 0赞

用栈实现十进制转换为二进制,用到模板库中的关于栈的部分函数。

以下是C++源代码:

  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. stack<int> sta;
  4. int main(){
  5. int n;
  6. while(cin>>n){
  7. while(!sta.empty()) sta.pop();
  8. if(n<0){
  9. cout<<"-";
  10. n=-n;
  11. }
  12. if(n==0){
  13. puts("0");
  14. continue;
  15. }
  16. while(n){
  17. if(n&1) sta.push(1);
  18. else sta.push(0);
  19. n>>=1;
  20. }
  21. while(!sta.empty()){
  22. cout<<sta.top();
  23. sta.pop();
  24. }
  25. puts("");
  26. }
  27. return 0;
  28. }

现在还有许多不懂的地方,以后再做注释和修改。

发表评论

表情:
评论列表 (有 0 条评论,307人围观)

还没有评论,来说两句吧...

相关阅读