黑马程序员技术交流社区
标题:
面试题之回文数的判断
[打印本页]
作者:
聂广强
时间:
2013-7-30 16:18
标题:
面试题之回文数的判断
看了之前的面试题一直认为回文数是一个老大难 但是昨天面试翻转字符串的时候突然发现 回文数也是可以这样简单进行判断
class Program
{//判断输入的字符串是否为回文数
static void Main(string[] args)
{
label:
Console.WriteLine( "请输入字符串判断是否为回文数");
string strWorld = Console.ReadLine();
if (check(strWorld))
{
Console.WriteLine("是回文数");
goto label;
}
else
{
Console.WriteLine("不是回文数");
}
Console.ReadKey();
}
private static bool check(string p)
{
bool boo=false;
char[] ch = p.ToCharArray();
for (int i = 0; i < ch.Length / 2; i++)
{
if (ch[i] == ch[ch.Length - 1 - i])
{
boo=true;
}
else
{
boo=false;
}
}
return boo;
}
}
复制代码
请广大马友看看 是否还有其他的 判断回文数的方法
作者:
黑骏马
时间:
2013-7-30 17:56
本帖最后由 黑骏马 于 2013-7-30 18:04 编辑
我把你的代码修改了下,看这样是不是更方便,代码可以重用:
namespace 判断回文数
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine( "请输入字符串判断是否为回文数");
string strWorld = Console.ReadLine();
checkHuiwen(strWorld);
Console.ReadKey();
}
public static void checkHuiwen(string p)
{
bool boo=false;
char[] ch = p.ToCharArray();
for (int i = 0; i < ch.Length / 2; i++)
{
if (ch[i] == ch[ch.Length - 1 - i]) //字符串两头对比
{
boo=true;
}
else
{
boo=false;
}
}
if (boo)
{
Console.WriteLine(p+"是回文数");
}
else
{
Console.WriteLine(p + "不是回文数");
}
}
}
}
复制代码
作者:
黑骏马
时间:
2013-7-30 18:04
本帖最后由 黑骏马 于 2013-7-30 18:24 编辑
然后这是我的代码:
namespace 判断回文数
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine( "请输入字符串判断是否为回文数");
string strWorld = Console.ReadLine();
//调用方法判断是否为回文数 //如需重用代码,把相应语句换成注释里的就行了
checkHuiwen(strWorld); /bool boo = checkHuiwen(strWorld); //int ch = checkHuiwen(strWorld);
//Console.WriteLine(boo); //Console.WriteLine(ch);
Console.ReadKey();
}
public static void checkHuiwen(string str) //public static bool checkHuiwen(string str) //public static int checkHuiwen(string str)
{
string _str = ""; //定义一个空字符串,用于存放翻转后的字符串
for (int i = str.Length - 1; i >= 0; i--)
{
_str += str[i]; //原字符串倒序排列
}
if (_str == str) //翻转后的字符串如果与原字符串相同则为回文数
{
Console.WriteLine(str + "是回文数"); //return true; //return 1;
}
else
{
Console.WriteLine(str + "不是回文数"); //return false; //return 0;
}
}
}
}
复制代码
作者:
lvjayj
时间:
2013-8-1 22:56
嗯,又学到了好多
作者:
黑骏马
时间:
2013-9-5 02:28
之前发的代码注释比较多,被编译器搞乱了,重新发一下:
namespace 判断回文数
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine( "请输入字符串判断是否为回文数");
string strWorld = Console.ReadLine();
checkHuiwen(strWorld);
Console.ReadKey();
}
public static void checkHuiwen(string str)
{
//定义一个空字符串,用于存放翻转后的字符串
string _str = "";
//原字符串倒序排列
for (int i = str.Length - 1; i >= 0; i--)
{
_str += str[i];
}
//翻转后的字符串如果与原字符串相同则为回文数
if (_str == str)
{
Console.WriteLine(str + "是回文数");
}
else
{
Console.WriteLine(str + "不是回文数");
}
}
}
}
复制代码
。
作者:
官方
时间:
2014-9-28 09:29
学习 路过~~
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2