题解 | #进制转换#
进制转换
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; } }#进制转换##大数除法#