您的位置:首页 > 其它

杭电2031(进制转换)

2015-05-10 22:47 375 查看
点击打开杭电2031

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


代码实现:

import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		char chs[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
		while(sc.hasNext()){
			int n = sc.nextInt();
			int r = sc.nextInt();
			boolean isNegative = false;
			if(n<0){
				n=-n;
				isNegative = true;
			}
			String str = "";
			while(n/r>0){
				str = chs[n%r]+str;
				n = n/r;
			}
			if(n%r!=0){
				str = chs[n%r]+str;
			}
			if(isNegative){
				str = "-" + str;
			}
			System.out.println(str);
		}
	}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: