统计对称数

问题描述

统计10到1000之间对称数的个数,并且打印所有对称数。所谓对称数(又称回文数)是指一整数从左往右看和从右往左看是相同的数字。例如: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);

	}

}

优化后

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();

	}

}

用Java特性优化后

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();
		
	}

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值