Base conversion (decimal to R base)

Input a decimal number N, convert it into R-based number and output.
Input
The input data contains multiple test instances, and each test instance contains two integers N (32-bit integer) and R (2<=R<=16, R<>10).
Output
Output the converted number for each test instance, 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

Repeatedly take the remainder from the number n to the number R, and the reverse order of the remainder is the result.
It is worth noting that the result of the output character plus a number is an integer. If you want to output a character, you must output a separate output character.
#include<iostream>
using namespace std;
char a[999];
int main()
{
    
    
	long long n;
	int r;
	while(cin>>n>>r)
	{
    
    
		int flag=0;
		if(n<0)
		{
    
    
			flag=1;
			n=-n;
		}
		int q=0;
		while(n!=0)
		{
    
    
			a[q]=n%r;
			n=n/r;
			q++;
		}
		q--;
		if(flag)
		cout<<"-";
		for(int i=q;i>=0;i--)
		{
    
    
			char q;
			if(a[i]<=9&&a[i]>=0)
			q=a[i]+'0';
			else
			q=a[i]-10+'A';
			cout<<q;
		}
		cout<<endl;
	}
	return 0;
} 

Guess you like

Origin blog.csdn.net/Huo6666/article/details/108095343