题目 1434: [蓝桥杯][历届试题]回文数字+位数和

题目描述

观察数字:12321,123321 都有一个共同的特征,无论从左到右读还是从右向左读,都是相同的。这样的数字叫做:回文数字。

本题要求你找到一些5位或6位的十进制数字。满足如下要求:
该数字的各个数位之和等于输入的整数。

输入
一个正整数 n (10< n< 100), 表示要求满足的数位和。

输出
若干行,每行包含一个满足要求的5位或6位整数。
数字按从小到大的顺序排列。
如果没有满足条件的,输出:-1

样例输入
44
样例输出
99899
499994
589985
598895
679976
688886
697796
769967
778877
787787
796697
859958
868868
877778
886688
895598
949949
958859
967769
976679
985589
994499

解题思路

先看代码,思路后补

代码如下

方法一:这个思路没问题,但放到判题机上拿不到全分,可以看看思路,然后用方法二

import java.util.Scanner;

/**
 * 
 * @author hf
 *
 */
public class Cyyw1434 {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int count = 0;
		for (int a = 1; a < 10; a++) {
			for (int b = 0; b < 10; b++) {
				for (int c = 0; c <= 10; c++) {
					if (2*a+2*b+c == n) {
						System.out.println(""+a+b+c+b+a);
						count++;
					}
				}
			}
		}
		for (int a = 1; a < 10; a++) {
			for (int b = 0; b < 10; b++) {
				for (int c = 0; c <= 10; c++) {
					if (2*a+2*b+2*c == n) {
						System.out.println(""+a+b+c+c+b+a);
						count++;
					}
				}
			}
		}
		if (count == 0) {
			System.out.println("-1");
		}
		sc.close();
	}
}

方法二:

import java.util.Scanner;

/**
 * 
 * @author hf
 *
 */
 
public class Cyyw1434 {
	public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        boolean f = true;//用于判断是否有满足条件的值
        for (int i = 10000; i <= 999999; i++) {
            if (f(i, n)) {
                System.out.println(i);
                f = false;
            }
        }
        //如果没有则输出-1
        if (f) {
            System.out.println(-1);
        }
    }
	
	/**
	 * 判断是否满足条件
	 * @param n
	 * @param s
	 * @return
	 */
    public static boolean f(int n, int s) {
        String str = n + ""; // 转换成字符串
        for (int i = 0; i < str.length() / 2; i++) {// 判断是否为回文数
            if (str.charAt(i) != str.charAt(str.length() - 1 - i)) {
                return false;
            }
        }
        int sum = 0; // 和
        for (int i = 0; i < str.length(); i++) {
            sum += str.charAt(i) - 48;// 转换成数字
        }
        if (sum != s) {// 判断和是否等于输入的数
            return false;
        }
        return true;
    }
}

运行示例

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_45481524/article/details/108487577