Skip to content

7-5 增一数

若一个正整数有 2n 个数位,后 n 位组成的数恰好比前 n 位组成的数大 1,则这个数称为增一数。例如 34、2526、233234 都是增一数。如果这个数还是某个数的平方,则称为平方增一数。你的任务就是判断任一给定正整数是否平方增一数。

输入格式:

输入在第一行中给出一个正整数 N(≤100),随后 N 行,每行给出一个不超过 231 的待判定的正整数。

输出格式:

对每个待判定的正整数,在一行中输出判定结果:如果是平方增一数,则输出 2;如果只是普通增一数,则输出 1;如果不是增一数,则输出 0。

输入样例:

tex
3
528529
2324
5678
3
528529
2324
5678

输出样例:

tex
2
1
0
2
1
0

Solution:

java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(in.readLine());
        for (int i = 0; i < n; i++) {
            String s = in.readLine();
            long length = s.length() / 2;
            long num = Long.parseLong(s);
            long x = (long) Math.pow(10, length);
            long left = num / x;
            long right = num % x;
            if (right - left == 1) {
                if (Double.toString(Math.sqrt(num)).matches("\\d+[.]0")) {
                    System.out.println(2);
                } else {
                    System.out.println(1);
                }
            } else {
                System.out.println(0);
            }

        }
    }
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(in.readLine());
        for (int i = 0; i < n; i++) {
            String s = in.readLine();
            long length = s.length() / 2;
            long num = Long.parseLong(s);
            long x = (long) Math.pow(10, length);
            long left = num / x;
            long right = num % x;
            if (right - left == 1) {
                if (Double.toString(Math.sqrt(num)).matches("\\d+[.]0")) {
                    System.out.println(2);
                } else {
                    System.out.println(1);
                }
            } else {
                System.out.println(0);
            }

        }
    }
}

Released under the MIT License.