Python基础练习 特殊回文
本文已参与「新人创作礼」活动,一起开启掘金创作之路。
问题描述
123321是一个非常特殊的数,它从左边读和从右边读是一样的。输入一个正整数n, 编程求所有这样的五位和六位十进制数,满足各位数字之和等于n 。
输入输出
- 输入格式
输入一行,包含一个正整数n。
- 输出格式
按从小到大的顺序输出满足条件的整数,每个整数占一行。
- 样例输入
52
- 样例输出
899998
989989
998899
-
数据规模与约定
1<=n<=54
Python版本 代码如下
n = eval(input())
for e in range(10000, 1000000): # 注意range的范围
s = str(e)
if e<100000:
sum=2*(int(s[0])+int(s[1]))+int(s[2])
if s[0] == s[-1] and s[1]==s[-2] and n==sum:
print(e)
else:
sum = 2*(int(s[0]) + int(s[1]) + int(s[2]))
if s[0]==s[-1] and s[1]==s[-2] and s[2]==s[-3] and n==sum:
print(e)
Java版本 代码如下
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
sc.nextInt();
// 两次for循环,分别代表两种情况的输出,暴力求解,不超时
for(int i = 10001; i < 100000; i++){ // 注意i的范围
int a = i /10000;
int b = (i % 10000) / 1000;
int c = (i % 1000) / 100;
int d = (i % 100) / 10;
int e = i % 10;
if(a + b + c + d + e == n && a == e && b == d){
System.out.println(i); // 与上文python的判断条件基本类
}
}
for(int i = 100001; i < 1000000; i++){ // 注意i的范围
int a = i /100000;
int b = (i % 100000) / 10000;
int c = (i % 10000) / 1000;
int d = (i % 1000) / 100;
int e = (i % 100) / 10;
int f = i % 10;
if(a + b + c + d + e + f == n && a == f && b == e && c == d){
System.out.println(i); // 与上文python的判断条件基本类
}
}
}
}
C语言版本 代码如下
#include<stdio.h>
int main()
{
int n, a[10];
scanf("%d", &n);
int i;
for(i = 10000; i <= 999999; i++){ // 注意i的范围
int t=i;
int s=0;
for(int j = 0; j < 6; j++){ // 注意j的范围
a[j]=t%10;
t/=10;
s+=a[j];
}
//判断两种情况,与上述两种语言的代码思想类似
if((i<=99999) && ((a[0]==a[4]) && (a[1]==a[3])) && (s==n)){
printf("%d\n", i);
}
if((i>=100000) && ((a[0]==a[5]) && (a[1]==a[4]) && (a[2]==a[3])) && (s==n)){
printf("%d\n", i);
}
}
return 0;
}