洛谷 B2161:十进制转二进制 ← 字符串 / 栈

​【题目来源】
https://www.luogu.com.cn/problem/B2161

【题目描述】
给定一个十进制整数 n,请将其转换为对应的二进制表示,并输出。

【输入格式】
输入包含一行,一个整数 n。

【输出格式】
输出一行,表示整数 n 的二进制表示(不含前导零)。

【输入样例二】
10

【输出样例二】
1010

【数据范围】
0≤n≤2^31-1。
提示:n=0 的情况需要特殊考虑。

【算法分析】
● 使用 C++ STL 中的 stack 实现进制转换的核心思路是利用栈“先进后出”的特性。
● 提示:n=0 的情况需要特殊考虑。
● 此题代码与“东方博宜OJ 1108”的代码一模一样:https://blog.csdn.net/hnjzsyjyj/article/details/158432409

【算法代码一:string】

#include <bits/stdc++.h>
using namespace std;

int main() {
    string s;
    int n;
    cin>>n;
    if(n==0) s="0";
    while(n) {
        s+=(n%2+'0');
        n/=2;
    }
    reverse(s.begin(),s.end());
    cout<<s;

    return 0;
}

/*
in:100
out:1100100
*/

【算法代码二:栈】

#include <bits/stdc++.h>
using namespace std;

stack<char> st;
int x;

int main() {
    cin>>x;
    if(x==0) st.push('0');
    while(x) {
        st.push(x%2+'0');
        x/=2;
    }

    while(!st.empty()) {
        cout<<st.top();
        st.pop();
    }

    return 0;
}

/*
in:100
out:1100100
*/




【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/158432409
https://blog.csdn.net/hnjzsyjyj/article/details/149136573
https://blog.csdn.net/hnjzsyjyj/article/details/146247521



 

​

posted @ 2026-02-26 22:58  Triwa  阅读(95)  评论(0)    收藏  举报