题解 | #进制转换#

进制转换

https://www.nowcoder.com/practice/0337e32b1e5543a19fa380e36d9343d7

#include <iostream>
#include "stack"
#include "vector"
using namespace std;
string divide(string str) {
    string result;
    int remain = 0;
    for (int i = 0; i < str.size(); i++) {
        int temp = remain * 10 + str[i] - '0';
        char tempChar='0'+temp/2;
        // str[i] = temp / 2 + '0';
        remain =( str[i]-'0')% 2;
        result+=tempChar;
    }
    int pos = 0;
    while (str[pos] == '0') {
        pos++;
    }
    if(result=="0") return "";//如果只有一个零,调用substr后还是会返回零
    else
    return result.substr(pos);
}
int main() {
    string a;
    while (cin >> a) { // 注意 while 处理多个 case
        // cout << a + b << endl;
        stack<int> bianryNums;
        vector<int> binary;
        while (a.size() > 0) {
            bianryNums.push((a[a.size() - 1] - '0') % 2);
            // binary.push_back((a[a.size() - 1] - '0') % 2);
            a = divide(a);
        }
        while(!bianryNums.empty()){
            cout<<bianryNums.top();
            bianryNums.pop();
        }
        // for (int i = binary.size() - 1; i >= 0; i--) {
        //     cout << binary[i];
        // }
        cout << endl;
    }
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

争当牛马还争不上
码农索隆:1.把简历改哈 2.猛投,狠投 3.把基础打牢 这样你在有机会的时候,才能抓住
点赞 评论 收藏
分享
07-02 18:09
门头沟学院 Java
苍穹外卖和谷粒商城这俩是不是烂大街了,还能做吗?
想去重庆的鸽子在吐槽:你不如把这俩做完自己搞明白再优化点再来问 何必贩卖焦虑
点赞 评论 收藏
分享
自由水:笑死了,敢这么面试不敢让别人说
点赞 评论 收藏
分享
07-02 13:52
武汉大学 golang
骗你的不露头也秒
牛客87776816...:😃查看图片
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务