首页 > 专题系列 > Java解POJ > POJ 1331 Multiply [解题报告] Java
2013
11-09

POJ 1331 Multiply [解题报告] Java

Multiply

问题描述 :

6*9 = 42″ is not true for base 10, but is true for base 13. That is, 6(13) * 9(13) = 42(13) because 42(13) = 4 * 131 + 2 * 130 = 54(10).

You are to write a program which inputs three integers p, q, and r and determines the base B (2<=B<=16) for which p * q = r. If there are many candidates for B, output the smallest one. For example, let p = 11, q = 11, and r = 121. Then we have 11(3) * 11(3) = 121(3) because 11(3) = 1 * 31 + 1 * 30 = 4(10) and 121(3) = 1 * 32 + 2 * 31 + 1 * 30 = 16(10). For another base such as 10, we also have 11(10) * 11(10) = 121(10). In this case, your program should output 3 which is the smallest base. If there is no candidate for B, output 0.

输入:

The input consists of T test cases. The number of test cases (T ) is given in the first line of the input file. Each test case consists of three integers p, q, and r in a line. All digits of p, q, and r are numeric digits and 1<=p,q, r<=1,000,000.

输出:

Print exactly one line for each test case. The line should contain one integer which is the smallest base for which p * q = r. If there is no such base, your program should output 0.

样例输入:

3
6 9 42
11 11 121
2 2 2

样例输出:

13
3
0

解题代码:

//* @author: [email protected]
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
 Scanner in=new Scanner(System.in);
 int a=in.nextInt();
 while((a--)!=0)
 {
	String s1=in.next();
	String s2=in.next();
	String s3=in.next();
	int max=0;
	for(int i=0;i< s1.length();i++)
	{
		char c=s1.charAt(i);
		int u=c-48;
		if(max< u)max=u;
	}
	for(int i=0;i< s2.length();i++)
	{
		char c=s2.charAt(i);
		int u=c-48;
		if(max< u)max=u;
	}
	for(int i=0;i< s3.length();i++)
	{
		char c=s3.charAt(i);
		int u=c-48;
		if(max< u)max=u;
	}
	boolean b=true;
	for(int o=max+1;o< 17;o++)
	{
		int w1=Integer.parseInt(s1, o);
		int w2=Integer.parseInt(s2, o);
		int w3=Integer.parseInt(s3, o);
		if(w1*w2==w3)
		{
			System.out.println(o);
			b=false;
			break;
		}
	}
	if(b)System.out.println(0);
  }
 }
}

  1. 很高兴你会喜欢这个网站。目前还没有一个开发团队,网站是我一个人在维护,都是用的开源系统,也没有太多需要开发的部分,主要是内容整理。非常感谢你的关注。

  2. 第二个方法挺不错。NewHead代表新的头节点,通过递归找到最后一个节点之后,就把这个节点赋给NewHead,然后一直返回返回,中途这个值是没有变化的,一边返回一边把相应的指针方向颠倒,最后结束时返回新的头节点到主函数。