关键词:
回文数 循环 条件语句
2
题目:
解决方法(朕):
1 packagecom.algorithm.java.blueBirdge;2
3 importjava.util.Scanner;4
5 public classPaliindrome2 {6 public static voidmain(String[] args){7 Scanner read =newScanner(System.in);8 int sum =read.nextInt();9 //int sum=0;
10 for(int i=10000;i<=999999;i++){11 if (i>=10000 && i<=99999) {12 //个位
13 int gewei5=i % 10;14 //十位
15 int shiwei5=(i % 100) / 10;16 //百位
17 int baiwei5=(i/100)%10;18 //千位
19 int qianwei5=(i / 1000) % 10;20 //万位
21 int wanwei5=i / 10000;22 //输出这样的五位数
23 if (gewei5== wanwei5 && ((shiwei5) == (qianwei5) && (gewei5+shiwei5+baiwei5+qianwei5+wanwei5==sum))) {24 //if(){
25 System.out.println(i);26 //}
27
28 }29 }30
31 //输出这样的六位数 999 999
32 else{33 //个位
34 int gewei6=i % 10;35 //十位
36 int shiwei6=(i % 100) / 10;37 //百位
38 int baiwei6=(i%1000)/100;39 //千位
40 int qianwei6=(i/1000)%10;41 //万位
42 int wanwei6=(i / 10000) % 10;43 //十万位
44 int shiwanwei6=i / 100000;45
46 if ((gewei6 == shiwanwei6 && ((shiwei6) == (wanwei6)) && (baiwei6)==qianwei6) && (gewei6+shiwei6+baiwei6+qianwei6+wanwei6+shiwanwei6==sum)) {47 //if(){
48 System.out.println(i);49 //}
50
51 }52 }53 }54 }55 }
解决方法(二):
package com.algorithm.java.blueBirdge;
import java.util.Scanner;
public class Palindorme3 {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
for (; ; ) {
int target = read.nextInt();
int sum[] = new int[1];
for (int i = 10000; i <= 999999; i++) {
sum[0] = i;
if (isPalindrome(sum)) {
if (sum[0] == target) {
System.out.println(i);
}
}
}
}
}
private static boolean isPalindrome(int[] sum) {
int sumTemp = 0;
int palindrome = 0;
int inputNumber = sum[0];
while (inputNumber != 0) {
int num = inputNumber % 10;
palindrome = palindrome * 10 + num;
inputNumber /= 10;
sumTemp += num;
}
boolean isok = palindrome == sum[0];
sum[0] = sumTemp;
return isok;
}
}