天天看點

十進制轉換為二進制非遞歸棧實作

用棧實作十進制轉換為二進制,用到模闆庫中的關于棧的部分函數。

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

現在還有許多不懂的地方,以後再做注釋和修改。

繼續閱讀