[PAT]1010. Radix (25)@Java解题报告

1010. Radix (25)

时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

Given a pair of positive integers, for example, 6 and 110, can this equation 6 = 110 be true? The answer is "yes", if 6 is a decimal number and 110 is a binary number.

Now for any pair of positive integers N1 and N2, your task is to find the radix of one number while that of the other is given.

Input Specification:

Each input file contains one test case. Each case occupies a line which contains 4 positive integers:
N1 N2 tag radix
Here N1 and N2 each has no more than 10 digits. A digit is less than its radix and is chosen from the set {0-9, a-z} where 0-9 represent the decimal numbers 0-9, and a-z represent the decimal numbers 10-35. The last number "radix" is the radix of N1 if "tag" is 1, or of N2 if "tag" is 2.

Output Specification:

For each test case, print in one line the radix of the other number so that the equation N1 = N2 is true. If the equation is impossible, print "Impossible". If the solution is not unique, output the smallest possible radix.

Sample Input 1:
6 110 1 10
Sample Output 1:
2
Sample Input 2:
1 ab 1 2
Sample Output 2:
Impossible

题意理解:

输入四个数:N1,N2,tag,radix,如果tag为1,则表明N1是radix进制,如果tag为2,则表明N2是radix进制。
N1,N2最多为10位数,且每一位都为0~9或者a~z,表示0~35
求是否有一个进制使得在此进制下,未知进制的数和另一个数在十进制下相等。存在则输出满足条件最小的进制,不存在则Impossible

网上大部分是用c++写的,参考了别人的代码。
有一个关键点是,c++中使用了long long类型,否则会越界。但是Java中没有longlong类型,所以使用BigInteger类

package go.jacob.day828;

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

/**
 * 1010. Radix (25)
 * @author Jacob
 * 关键点:用BigInteger代替Long
 */
public class Demo2 {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String n1 = sc.next(), n2 = sc.next();
		int tag = sc.nextInt(), radix = sc.nextInt();
		// 方便计算,把n1当做已知进制,n2未知
		if (tag == 2) {
			String tmp = n1;
			n1 = n2;
			n2 = tmp;
		}
		//将n1转成数字
		BigInteger num1 = str2Num(n1, radix);
		//找出num1中的最大数字
		BigInteger low=findBiggest(n2);
		BigInteger minRadix=BigInteger.ZERO;
		BigInteger left=low.add(BigInteger.ONE);
		BigInteger right=num1.max(BigInteger.valueOf(50)).add(BigInteger.ONE);
		while(left.compareTo(right)!=1){
			//二分法,mid为left+(right-left)/2;BigInteger的写法与一般写法不同
			BigInteger mid=left.add(right).divide(BigInteger.valueOf(2));
			BigInteger tmpValue=BigInteger.ZERO;
			//设置标志,记录tmpValue与num1的大小关系
			int flag=-1;
			for(int i=0;i= '0' && c <= '9')
			value = BigInteger.valueOf(c - '0');
		else
			value = BigInteger.valueOf(c - 'a' + 10);
		return value;

	}

}









你可能感兴趣的:(PAT)