利用短除法,一直除至0,输出的数通过栈反序输出。
通过字符数组接受数据,转换成int存入队列q1中,将队列中的数据一次取出对2取余,整除,存入第二个队列q2,直到第一个队列为空,将去q1=q2;循环,直到q1为空
#include<iostream>
#include<cstring>
#include<queue>
#include<stack>
using namespace std;
int main(){
char ch[35];
while(cin>>ch){
queue<int> q1;
stack<int> s1;
for(int i=0;i<strlen(ch);i++){//装换为int
int temp=ch[i]-'0';
q1.push(temp);//存入队列
}
while(!q1.empty()){//结束条件,队列为空
int cf=0;//进位;
queue<int> q2;//临时队列,存中间数据
while(!q1.empty()){
int temp=q1.front();
// cout<<temp<<endl;
q1.pop();
int sum=cf*10+temp;
if(sum%2==1){
cf=1;
}else{
cf=0;
}
int next=sum/2;
//判断第一个数为0的情况
if(next==0){
if(!q2.empty()){
q2.push(next);
}
}else{
q2.push(next);
}
}
q1=q2;
s1.push(cf);//结果放入栈中
}
while(!s1.empty()){//输出
cout<<s1.top();
s1.pop();
}
cout<<endl;
}
return 0;
}

京公网安备 11010502036488号