题解 | #进制转换#

进制转换

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

#include <iostream>
#include <ostream>
#include <cstring>
using namespace std;

void div2(char* data) {             //将用字符串表示的非负整数data除以2
    int remainder = 0;              //余数
    char* quotient = new char[100]; //商
    for (int i = 0; i < strlen(data); i++) {
        quotient[i] = (data[i] - '0' + remainder * 10) / 2 + '0';
        remainder = (data[i] - '0') % 2;
    }
    if (quotient[0] == '0' && strcmp(quotient, "0")) {
        quotient++;
    }
    strcpy(data, quotient);
}

int main() {
    char* a = new char[100];        //存放输入的数据
    int* stack = new int[1000];     //数字栈,用于存放转换成的二进制数
    int top;                        //栈顶指针
    while (cin >> a) {
        top = 0;                    //栈顶指针置零
        if (!strcmp(a, "0")) {      //a == 0
            cout << 0 << endl;
            continue;
        }
        while (strcmp(a, "0")) {                    //a != 0
            int len = strlen(a);
            stack[top++] = (a[len - 1] - '0') % 2;  //余数(a % 2)入栈
            div2(a);                                //a = a / 2
        }
        while (top != 0) {
            cout << stack[--top];                   //余数依次出栈并输出
        }
        cout << endl;
    }
}

#进制转换##大数除法#
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-02 17:58
点赞 评论 收藏
分享
05-26 10:24
门头沟学院 Java
qq乃乃好喝到咩噗茶:其实是对的,线上面试容易被人当野怪刷了
找工作时遇到的神仙HR
点赞 评论 收藏
分享
05-20 13:59
门头沟学院 Java
米黑子米黑子:你这个成绩不争取下保研?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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