Java练习 SDUT-1253_进制转换

进制转换

Time Limit: 1000 ms Memory Limit: 65536 KiB

Problem Description

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

Input

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

Output

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

Sample Input

7 2
23 12
-4 3

Sample Output

111
1B
-11

Hint

Source

HDOJ

进制转换的模板。

import java.util.*;

public class Main {

    static char a[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};//类似全局变量。
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int f,n,r;
        while(cin.hasNext())
        {
        	f = 0;
        	n = cin.nextInt();
        	r = cin.nextInt();
        	if(n==0)//0需要特判,否则没有输出。
        	{
        		System.out.println(0);
        		continue;
        	}
        	if(n<0)
        	{
        		f = 1;
        		n = -n;
        	}
        	if(f==1)
        		System.out.print("-");
        	get(n,r);
        	System.out.println();
        }
        cin.close();
    }
    public static void get(int n,int r)
    {
    	if(n==0)
    		return;
    	int x = n%r;
    	get(n/r,r);
    	System.out.print(a[x]);
    }
}
原文地址:https://www.cnblogs.com/luoxiaoyi/p/9711981.html