ORIGIN

HDU-2031 进制转换

ACM 1 mins280 words

进制转换

输入一个十进制数N,将它转换成R进制数输出。

Input

输入数据包含多个测试实例,每个测试实例包含两个整数N(32位整数)和R(2<=R<=16, R<>10)。

Output

为每个测试实例输出转换后的数,每个输出占一行。如果R大于10,则对应的数字规则参考16进制(比如,10用A表示,等等)。

Sample Input

1
2
3
7 2
23 12
-4 3

Sample Output

1
2
3
111
1B
-11

Analysis

Using the math way of transforming the decimal to any number. And store each digit in array. when he digit is over 10, then using the corresponding letters to represent the digit.

Code

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
#include <cstdio>
#include <cmath>

using namespace std;

int main(){
int n, r;
while(scanf(cin >> n >> r){
int temp = n;
n = abs(n);
int i;
int arr[100000];
for(i = 0; n != 0 ; i ++){
arr[i] = n % r;
n = n / r;
}
if(temp < 0) printf("-");
for(int j = i - 1; j >= 0; j --){
if(j == 0){
if(arr[j] >= 10)
printf("%c\n", arr[j] + 55);
else
printf("%d\n", arr[j]);
} else {
if(arr[j] >= 10)
printf("%c", arr[j] + 55);
else
printf("%d", arr[j]);
}
}
}
return 0;
}
TOP
COMMENT
  • ABOUT
  • |
o_oyao
  The Jigsaw puzzle is incomplete with even one missing piece. And I want to be the last piece to make the puzzle complete.
Like my post?
Default QR Code
made with ❤️ by o_oyao
©o_oyao 2019-2024

|