C/C++ Programming Learning-Week 10 ④ Base Conversion

Topic link

Title description

Input a decimal number N, convert it into R-based number and output.

Input
input data contains multiple test cases, each test case contains two integers N (32-bit integer) and R (2<=R<=16, R<>10).

Output
outputs the converted number for each test instance, and each output occupies one line. If R is greater than 10, the corresponding number rule refers to hexadecimal (for example, 10 is represented by A, etc.).

Sample Input

7 2
23 12
-4 3

Sample Output

111
1B
-11

Ideas

Convert the decimal number N into an R number and output. Here I wrote a hexadecimal conversion function. Of course, there are many ways to solve this problem, and I don’t have to use my method.

C++ code 1 (decimal conversion function template):

#include<bits/stdc++.h>
using namespace std;
char num[100];
char s[36] = {
    
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
int n, m, step;
void solve(int a, int b)		//十进制数a转化为b进制数 
{
    
    
	step = 0;
	if(a < 0)
	{
    
    
		cout << "-";
		a = -a;
	}
	while(a)
	{
    
    
		num[step++] = s[a % b];
		a /= b;
	}
	for(step -= 1; step >= 0; step--)
		cout << num[step];
	cout << endl;
}
int main ()
{
    
    
    while(cin >> n >> m)	//十进制数n转化为m进制数 
		solve(n, m);
    return 0;
}

Of course you can also write like this:

#include<bits/stdc++.h>
using namespace std;
char num[10005];
int main()
{
    
    
	ios::sync_with_stdio(false);
	long long int n, r;
	while(cin >> n >> r)
	{
    
    
		memset(num, 0, sizeof(num));
		int i = 0, m, flag = 0;
		if(n < 0)
		{
    
    
			flag = 1;
			n = -n;
		}
		while(n >= r)
		{
    
    
			m = n % r;
			if(m < 10) num[i++] = m + 48;
			else if(m == 10) num[i++] = 'A';
			else if(m == 11) num[i++] = 'B';
			else if(m == 12) num[i++] = 'C';
			else if(m == 13) num[i++] = 'D';
			else if(m == 14) num[i++] = 'E';
			else if(m == 15) num[i++] = 'F';
			n /= r;
		}
		if(0 < n && n < 10) num[i++] = n + 48;
		else if(n == 10) num[i++] = 'A';
		else if(n == 11) num[i++] = 'B';
		else if(n == 12) num[i++] = 'C';
		else if(n == 13) num[i++] = 'D';
		else if(n == 14) num[i++] = 'E';
		else if(n == 15) num[i++] = 'F';
		i--;
		if(flag) cout << "-";
		for(; i >= 0; i--)
			cout << num[i];
		cout << endl;
	}
	return 0;
}

It can also be written like this:

#include<bits/stdc++.h>
using namespace std;
int main()
{
    
    
	char s1[] = "0123456789ABCDEF", s2[100]; //最大为十六进制,所以只需到F就可以了
	int t, r;
	while(cin >> t >> r)
	{
    
    
		int flag = 0,x;
		if(t < 0)
		{
    
    
			t = -t; //判断是否是负数
			flag = 1;//标记
		}
		for(int i = 0; ; i++)
		{
    
    
			if(t == 0) break;
			s2[i] = s1[t % r]; //求余数并赋值s2,一直循环,直到t=0
			t /= r;
			x = i; //记录一下字符串的长度
		}
		if(flag == 1) cout << '-';
		for(int i = x; i >= 0; i--)
			cout << s2[i]; //逆序输出
		cout << "\n";
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_44826711/article/details/113098191