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

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

以下是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;
}

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

发布了27 篇原创文章 · 获赞 50 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/baidu_41774120/article/details/85224740