Problem Description
Count the number of symmetric numbers between 10 and 1000, and print all symmetric numbers. The so-called symmetric number (also known as the palindrome) means that an integer is the same number when viewed from left to right and from right to left. For example: 12321,6226.
public class Test3_1_1 { static boolean isSym(int n) { int over=n%10; int q=n; q/=10; while (q!=0) { over=over*10+q%10; q/=10; } if (n==over) return true; return false; } public static void main(String[] args) { // TODO Auto-generated method stub int count=0; for (int i=10;i<=1000;i++) { if (isSym(i)==true) { count++; System.out.println(i); } } System.out.println("count="+count); } }
Optimized
public class Test3_1_2 { static void doc() { int[] a=new int[20]; int count=0; int k,i,j; for (int n=10;n<=1000;n++) { int temp=n; k=0; while (temp!=0) { a[k++]=temp%10; temp /= 10; } for (i=0,j=k-1;i<j;i++,j--) if (a[i]!=a[j]) break; if (i==k/2) { count++; System.out.println(n); } } System.out.println("count="+count); } public static void main(String[] args) { // TODO Auto-generated method stub doc(); } }
After optimization with Java features
public class Test3_1_3 { static void f() { int count=0; ok:for (int n=10;n<=1000;n++) { String s=Integer.toString(n); for (int i=0;i<s.length();i++) { if (s.charAt(i)!=s.charAt(s.length()-1-i)) continue ok; } count++; System.out.println(n); } System.out.println("count="+count); } public static void main(String[] args) { // TODO Auto-generated method stub f(); } }