题解 | #进制转换#

进制转换

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

//KY_26会了,这道题就很简单。模拟竖式除法即可
#include "stdio.h"
#include "string"
#include "algorithm"
using namespace std;

string conversion(string num){//十进制转二进制
    string str;
    int len = num.size();
    for (int i = 0; i < len; ) {
        int remainder = 0;
        for (int j = i; j < len; ++j) {
            int k = (remainder*10+num[j]-'0')%2;
            num[j] = (remainder*10+num[j]-'0')/2+'0';
            remainder = k;
        }
        str += char (remainder+'0');
        while (num[i]=='0')
            ++i;
    }
    reverse(str.begin(),str.end());
    return str;
}

int main(){
    char buf[32];
    while (scanf("%s",buf)!=EOF){
        string str = buf;
        printf("%s\n", conversion(str).c_str());
    }
}

全部评论

相关推荐

我即大橘:耐泡王
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务