You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

十进制转二进制转换器结果顺序颠倒,求正确实现方案

十进制转二进制转换器的修正与优化方案

问题分析

当前代码的核心问题是:每次将取余得到的二进制低位字符追加到字符串末尾,最终输出的是逆序的二进制结果。另外还有一处边界漏洞:输入0时会返回空字符串,不符合预期。


修正现有代码的两种简单方案

方案1:反转结果字符串

在返回前把生成的逆序字符串反转,即可得到正确顺序,同时补充输入0的处理逻辑:

#include <iostream>
#include <algorithm> // 用于reverse函数

using namespace std;

string DecimaltoBinary(int d){
    if (d == 0) { // 处理0的边界情况
        return "0";
    }
    string decimal;
    while(d != 0){
        decimal += (d % 2 == 0 ? "0": "1");
        d /= 2;
    }
    reverse(decimal.begin(), decimal.end()); // 反转字符串得到正序结果
    return decimal;
}

int main(){
    int decimal;
    cout<<"Input the decimal number: "<<endl;
    cin>>decimal;
    cout<<DecimaltoBinary(decimal)<<endl;
    return 0;
}

方案2:每次将字符插入到字符串头部

不追加到末尾,而是把每次得到的二进制位插入到字符串开头,直接生成正序结果:

#include <iostream>

using namespace std;

string DecimaltoBinary(int d){
    if (d == 0) {
        return "0";
    }
    string binary;
    while(d != 0){
        binary = (d % 2 == 0 ? "0": "1") + binary; // 新字符插入到字符串头部
        d /= 2;
    }
    return binary;
}

int main(){
    int decimal;
    cout<<"Input the decimal number: "<<endl;
    cin>>decimal;
    cout<<DecimaltoBinary(decimal)<<endl;
    return 0;
}

其他更规范的实现方法

方法1:利用栈结构

栈的“后进先出”特性天然适配逆序收集、正序输出的场景:

#include <iostream>
#include <stack>

using namespace std;

string DecimaltoBinary(int d){
    if (d == 0) {
        return "0";
    }
    stack<char> bits;
    while(d != 0){
        bits.push( (d % 2 == 0 ? '0' : '1') );
        d /= 2;
    }
    string binary;
    while(!bits.empty()){
        binary += bits.top();
        bits.pop();
    }
    return binary;
}

int main(){
    int decimal;
    cout<<"Input the decimal number: "<<endl;
    cin>>decimal;
    cout<<DecimaltoBinary(decimal)<<endl;
    return 0;
}

方法2:使用C++标准库函数

借助<bitset>可以快速实现整数转二进制字符串,适合固定位数的整数场景:

#include <iostream>
#include <bitset>

using namespace std;

string DecimaltoBinary(int d){
    if (d == 0) {
        return "0";
    }
    // 将整数转为32位二进制字符串,再去除前置多余的0
    string binary = bitset<32>(d).to_string();
    return binary.substr(binary.find_first_not_of('0'));
}

int main(){
    int decimal;
    cout<<"Input the decimal number: "<<endl;
    cin>>decimal;
    cout<<DecimaltoBinary(decimal)<<endl;
    return 0;
}

内容的提问来源于stack exchange,提问作者FranciscoSegura88

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 09:31:01