对称数的简单实现

在百度面试题中看到这样一个题,可能比较老套了,这里为了学习,自己写了改写了个简单算法。

我们把一个数字倒着读和原数字相同的数字称之为对称数,

(例如1,121,88,8998),不考虑性能,请找出1—10000(n)之间的对称数,

private List<int> Getsymmetry(int num)
{
  List<int> numList = new List<int>();
  bool bIsEqual = true;
  for (int j = 1; j <= num; j++)
  {
    string number = j.ToString();
    for (int i = 0; i < number.Length / 2; i++)
    {
      if (number[i] != number[number.Length - 1 - i])
      {
        bIsEqual = false;
        break;
      }
        bIsEqual = true;
    }

    if (bIsEqual)
    {
      numList.Add(j);
    }

  }
  return numList;
}

这里的numList便保存了我们所有(1到n)的对称数

在网上看到有位大哥这样写,很简单了。

//这个方法是将数的顺序反转,判断反转后的数与原来的数是否相等。
public static bool findNumber(int n)
{
  int nValue = 0;
  int temp = n;  
  while (temp > 0)
  {
    nValue = nValue * 10 + temp % 10;
    temp /= 10;
  }
  return (nValue == n);
}

算法是个复杂的东东。继续学习中。

共同学习,共同进步!
原文地址:https://www.cnblogs.com/lideng/p/2982779.html