C# 统计回文数

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 回文数
{
class Program
{
public void tongji()
{int j=0;

for(double i=11111;i<=99999;i++){
double a = i / 10000;
double b = i % 10000 / 1000;
double c = i % 100 / 10;
double d = i % 10;
if (d==a&&c==b)
j++;

}
Console.WriteLine("五位回文数的个数:{0}", j);
}
static void Main(string[] args)
{
Console.WriteLine("1.判断回文数");
Console.WriteLine("2.统计五位回文数");
string k = Console.ReadKey().Key.ToString();
Console.Clear();
switch (k)
{
case "D1":
Console.Write("请输入一个五位整数:");
var x = Convert.ToInt32(Console.ReadLine());
var wan = x / 10000;
var qian = x % 10000 / 1000;
var shi = x % 100 / 10;
var ge = x % 10;
if (ge == wan && shi == qian)
Console.WriteLine("{0},这个数是回文数", x);
else
Console.WriteLine("{0},这个数不是回文数", x);
break;
case "D2": Program a1 = new Program();
a1.tongji();
break;
}
}
}
}

方法tongji()做出来答案为0,谁能帮我改下

请参考:

public class Program
    {
        public static void Main(string[] args)
        {
            ConsoleKeyInfo cki;
            do
            {
                Console.WriteLine("请输入一个字符串进行回文测试:");
                string str = Console.ReadLine();
                if (str.IsPalindrome())
                    Console.WriteLine("是回文串!");
                else
                    Console.WriteLine("不是回文串!");
                Console.WriteLine("输入Enter继续,其他键结束!");
                cki = Console.ReadKey();
            }
            while (cki.KeyChar == 13);
        }
    }
    public static class StrEx
    {
        public static bool IsPalindrome(this string str)
        {
            if (string.IsNullOrEmpty(str)) return false;
            int iCount = str.Length / 2;
            for (int i = 0; i < iCount; i++)
            {
                if (str[i] != str[str.Length - i - 1])
                {
                    return false;
                }
            }
            return true;
        }
    }

PS :以上代码在vs2008中测试通过,你可以在任意可调用StrEx类的地方使用上面的字符串扩展方法,如:

 "字符串实例".IsPalindrome()

int a;a.ToString().IsPalindrome()

去判断是否回文!

温馨提示:内容为网友见解,仅供参考
第1个回答  2014-03-08
//把double 类型改成 int ,因为double除以int 返回小数的 
在这个区间中 将永远无法满足 d == a && c == b
int j = 0;
            for (int i = 11111; i <= 99999; i++)
            {
                int a = i / 10000;
                int b = i % 10000 / 1000;
                int c = i % 100 / 10;
                int d = i % 10;
                if (d == a && c == b)
                    j++;
            }
            MessageBox.Show(string.Format("五位回文数的个数:{0}", j));

本回答被网友采纳
第2个回答  2015-10-05
//求1到n的所有回文数

#include <cstdio>
#include <algorithm>

using namespace std;

int a[1000];
int i,n,j,k;

int main()
{
scanf("%d",&n);
for (i=1;i<=n;i++)
{
int t=i;
int sum=0;
while (t)
{
a[++sum]=t%10;
t=t/10;
}
j=1;k=sum;
bool f=false;
while (f==false)
{
if (a[k]!=a[j]) break;
if (k==j || k<j) f=true;
k--;j++ ;
}
if (f==true) printf("%d ",i);
}
}
相似回答