算法设计-模拟进制转换
Posted Mount256
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法设计-模拟进制转换相关的知识,希望对你有一定的参考价值。
文章目录
1. 十进制转二进制
#include <stdio.h>
#include <vector>
using namespace std;
int main()
unsigned int n;
while (scanf("%d", &n) != EOF)
vector<int> binary; // 写在里面,每次循环都会被清空
while (n != 0)
binary.push_back(n % 2);
n = n / 2;
for (int i = binary.size() - 1; i >= 0; i--)
printf("%d", binary[i]);
printf("\\n");
return 0;
2. 十进制转r进制(2<=r<=36)
#include <stdio.h>
#include <vector>
using namespace std;
int main()
int num, r;
int tmp;
printf("请输入数字num以及r进制:\\n");
while (scanf("%d %d", &num, &r) != EOF)
vector<char> result;
tmp = 0;
while (num > 0)
tmp = num % r;
if (tmp < 10)
result.push_back(tmp + '0');
else
result.push_back(tmp - 10 + 'A');
num = num / r;
for (int i = result.size() - 1; i >= 0; i--)
printf("%c", result[i]);
printf("\\n");
return 0;
3. 将M进制数X转换为N进制数(2<=M, N<=36)
#include <cstdio>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
int M, N;
string X;
int tmp, num;
printf("请输入M以及N,和M进制下的数字X:\\n");
while (cin >> M >> N >> X)
vector<char> result;
num = 0;
// 先将M进制数转换为十进制数
for (int i = 0; i < X.size(); i++)
if (i == 0) // 计算M^i
tmp = 1;
else
tmp = M * tmp;
int index = X.size() - i - 1;
if ('0' <= X[index] && X[index] <= '9')
num += (X[index] -'0') * tmp;
else if ('A' <= X[index] && X[index] <= 'Z')
num += (X[index] -'A' + 10) * tmp;
else if ('a' <= X[index] && X[index] <= 'z')
num += (X[index] -'a' + 10) * tmp;
//printf("%d\\n", num);
// 再将十进制数转换为N进制数
while (num > 0)
tmp = num % N;
if (tmp < 10)
result.push_back(tmp + '0');
else
result.push_back(tmp - 10 + 'A');
num = num / N;
for (int i = result.size() - 1; i >= 0; i--)
printf("%c", result[i]);
printf("\\n");
return 0;
以上是关于算法设计-模拟进制转换的主要内容,如果未能解决你的问题,请参考以下文章