(高精度演算4.7.26)POJ 1220 NUMBER BASE CONVERSION(高精度数の任意進数の変換——方法:ba 1----->10進数---->ba 2)

2052 ワード

package com.njupt.acm;

import java.math.BigInteger;
import java.util.Scanner;

public class POJ_1220_1 {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		
		int t = scanner.nextInt();
		
		while(t > 0){
			BigInteger ba1 = scanner.nextBigInteger();
			BigInteger ba2 = scanner.nextBigInteger();
			BigInteger sum = new BigInteger("0");
			
			String str = scanner.next();
			
			int len = str.length();
			int i;
			int count = 0;
			int temp;
			for(i = len - 1; i >= 0 ; --i){// ba1 10 
				char w = str.charAt(i);
				temp = 0;
				if(Character.isDigit(w)){
					temp = w - '0';
				}else if(Character.isLowerCase(w)){
					temp = w - 'a' + 36;
				}else if(Character.isUpperCase(w)){
					temp = w - 'A' + 10;
				}
				
				sum = sum.add(new BigInteger(temp + "").multiply(ba1.pow(count++)));
				
			}

			BigInteger zero = new BigInteger("0");
			int top = 0;
			int stack[] = new int[2000];
			while(sum.compareTo(zero) != 0){// ba2 
				stack[++top] = sum.mod(ba2).intValue();
				sum = sum.divide(ba2);
			}
			
			System.out.println(ba1+" "+str);
			System.out.print(ba2+" ");
			if(top == 0){
				System.out.print(0);
			}
			
			while(top != 0){
				char w = 0;
				temp = stack[top--];
				if(temp < 10){
					w = (char) (temp +'0');
				}else if(temp>= 10 && temp < 36){
					w = (char) (temp +'A' - 10);
				}else if(temp >= 36){
					w = (char) (temp + 'a' - 36);
				}
				
				System.out.print(w);
			}
			
			System.out.println();
			System.out.println();
			t--;
		}
		
	}
}