一开始总是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());
}
}
}
}