[HDU] [2031] Base Conversion

Problem Description

Loading...

Problem Analysis

A base conversion problem
A bit of a hassle
Mainly because it involves digits beyond base 10
You need to output them as
10-A 11-B 12-C 13-D 14 E 15 F
in that style
But once you’ve got the basic idea of storing digits in an array
it’s still fairly easy to solve

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include<stdio.h>
#include<string.h>
int Rt(int a[],int N,int R) {
	int i;
	for(i=0; N>=R; i++) {
		a[i]=N%R;
		N=N/R;
	}
	a[i]=N;
	return i;
}
int main() {
	int x,i,j,N,R;
	int a[1000];
	char s[1000];
	while(scanf("%d %d",&N,&R)!=EOF) {
		memset(a,0,sizeof(a));
		memset(s,0,sizeof(s));
		if(N>=0)
			x=1;
		else {
			x=0;
			N=-N;
		}
		i=Rt(a,N,R);
		for(j=0; j<=i; j++) {
			if(a[i-j]==10)
				s[j]='A';
			else if(a[i-j]==11)
				s[j]='B';
			else if(a[i-j]==12)
				s[j]='C';
			else if(a[i-j]==13)
				s[j]='D';
			else if(a[i-j]==14)
				s[j]='E';
			else if(a[i-j]==15)
				s[j]='F';
			else {
				s[j]=a[i-j]+'0';
			}
		}
		if(x==0)
			printf("-");
		printf("%s\n",s);
	}
	return 0;
}

======20160531 Addendum======

Solved with Recursion
the process of dividing by k, taking the remainder, and outputting in reverse order
(the mechanism of a recursive function is to finish running the nested call first)
(that is, depth first)
plus a character array to hold the mapping
this makes the code very concise

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include<stdio.h>
#include<string.h>
char mi[]= {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
void f(int m,int k) {
	if(m<k) {
		printf("%c",mi[m]);
		return ;
	} else {
		f(m/k,k);
		printf("%c",mi[m%k]);
	}
}
int main() {
	int n,R;
	while(scanf("%d %d",&n,&R)!=EOF) {
		if(n<0) {
			printf("-");
			n=-n;
		}
		f(n,R);
		printf("\n");
	}
	return 0;
}
This post is licensed under CC BY-NC-SA 4.0. If it helped, or if you have anything to say, the comment box below is open.
Page views —
Unique visitors —

Loading...