Digital Square
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 2037 Accepted Submission(s): 818
Problem Description
Given an integer N,you should come up with the minimum
nonnegative integer M.M meets the follow condition: M
2%10
x=N (x=0,1,2,3....)
Input
The first line has an integer T( T< = 1000), the number of test cases.
For each case, each line contains one integer N(0<= N <=10 9), indicating the given number.
For each case, each line contains one integer N(0<= N <=10 9), indicating the given number.
Output
For each case output the answer if it exists, otherwise print “None”.
Sample Input
3 3 21 25
Sample Output
None 11 5
Source
题目大意应该好理解,给你一个数,让你找到另外一个数X需要满足两个条件:
①X是个平方数。②X的后缀包含题目所给的数
比如题上给了21,我们可以找到11——因为11的平方是121,21就在121后边。
再比如说123456,我们可以找到42616,因为42616的平方是1816123456,后缀是123456。
解题思路:
举个栗子,,1x1=1,,9*9=81,他们的平方后缀都是1,所以如果题目给了一个数比如说是50001,它对应的答案是多少目前不知道,但是至少我知道这个答案的个位数不是1就是9,这样我就可以固定个位数,去十位数找。
11的平方?21的平方?31?41?51?都不是。。。一直找到91都没有,再按9找。。终于我在49找到了49的平方是2401,这样后缀01确定了!可以去更高位找了。
以此类推,我找到了249 的平方62001,确定了后缀001
以此类推,我找到了6249的平方39050001,确定了后缀50001。
注意事项:
不能找到了答案就return,因为题目说了要找一个最小的,,比如输入一个81,,按上述方法一定先找到41(41x41=1681,后缀也是81),但是我要找的是9,所以应该都找一遍,把可能的答案中的那个最小的那个保留下来。
一位一位地向更高位找,如果位数比题目给的数都大。。。。就可以return了(结束条件)。
代码如下:
import java.util.*;
public class Main
{
public static final int MAX = Integer.MAX_VALUE;
public static long t;
public static long answer=MAX;
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
while((n--)>0)
{
answer = MAX;
t = in.nextLong();
digui(0,1);
if(answer==MAX)System.out.println("None");
else System.out.println(answer);
}
}
public static boolean digui(long x,long flag)
{
if((x*x)%flag==t)
{
answer = Math.min(answer, x);
System.out.println(answer);
return false;
}
if(flag>t*10)return false;
for(int i=0 ; i<=9 ; i++)
{
long tem = x+flag*i;
if(tem*tem%(flag*10)==t%(flag*10))
{
digui(x+flag*i,flag*10);
}
}
return true;
}
}