栈--二进制转化

来源:互联网 发布:造价数据库 编辑:程序博客网 时间:2024/05/23 14:10

c

#include <stdio.h>//将十进制转换成二进制数字int main(){    int stack[10000],top=0;//创建一个栈    int m;    scanf("%d",&m);    printf("(%d)10 == (",m);    while(m!=0){        stack[top++]=m%2;//将元素推进栈中        m/=2;    }    while(top){        printf("%d",stack[--top]);//取出栈顶元素,将栈顶元素弹出    }    printf(")2\n");    return 0;}

c++

#include <iostream>#include <stack>using namespace std;//将十进制转换成二进制数字int main(){    int m;//m 为数字    cin>>m;    stack<int>s;//创建一个栈    cout<<"("<<m<<")10 == (";    while(m!=0)    {        s.push(m%2);//将元素推进栈中        m/=2;    }    while(!s.empty())    {        cout<<s.top();//取出栈顶元素        s.pop();//将栈顶元素弹出    }    cout<<")2\n";    return 0;}
0 0