HDUOJ2013进制转换

一开始总是WA,果然还是我太菜。。。。

后来发现10 的2 进制输出的结果不对,int k=0;a[k++]=(int) n;这就是错误的根源,改成a[(count-count1-1)]=(int) n;就对了

哎,其实自己都觉得方法有点麻烦,网上看到有大佬用的递归,代码看上去简单很多.

import java.util.Scanner;

public class HDU2031 {

	public static void main(String[] args) {
		Scanner in=new Scanner(System.in);
		while(in.hasNext()) {
			long n1=in.nextInt();
			int r=in.nextInt();
			long n=Math.abs(n1);
			long m=n;
			int count=0,count1=0,k=0;
			while(n>Math.pow(r, count))count++;
			int[]a=new int [count];
			for(int i=0;i<count;i++) {
				a[i]=0;
			}
			while(true) {
				if(n/r==0&&k<count) {
					a[(count-count1-1)]=(int) n;
					break;
				}
				while(n/r!=0) {
					n=n/r;
					count1++;
				}
				a[(count-count1-1)]=(int) n;
				int b=(int) (m-n*Math.pow(r, count1));
				n=b;
				count1=0;
				m=b;
			}
			if(n1<0) System.out.print("-");
			for(int j=0;j<count-1;j++) {
				if(a[j]>=0&&a[j]<=9) {
					System.out.print(a[j]);
				}
				else if(a[j]>9) {
					System.out.print(Integer.toHexString(a[j]).toUpperCase());
				}
			}
			if(a[count-1]>=0&&a[count-1]<=9) {
				System.out.println(a[count-1]);
			}
			else {
				System.out.println(Integer.toHexString(a[count-1]).toUpperCase());
			}
		}
		
	}

}


            

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值