东方博宜OJ 1108:正整数N转换成一个二进制数 ← 字符串 / 栈

【题目来源】
https://oj.czos.cn/p/1108

【题目描述】
输入一个不大于 32767 的整数 n,将它转换成一个二进制数。

【输入格式】
输入只有一行,包括一个整数 n(0≤n≤32767)。​​​​​​​

【输出格式】
输出只有一行。​​​​​​​

【输入样例一】
100

【输出样例一】
1100100

【输入样例二】
0

【输出样例二】
0

【数据范围】
0≤n≤32767

【算法分析】
使用 C++ STL 中的 stack 实现进制转换的核心思路是利用栈“先进后出”的特性。

【算法代码一: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/149136573
https://blog.csdn.net/hnjzsyjyj/article/details/146247521




 

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