C# 以编程方式检查数字是否为回文
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1785811/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Programmatically check if a number is a palindrome
提问by Fábio Antunes
This sounds like homework, yes it is (of someone else), I asked a friend of mine who is learning C# to lend me some of his class exercises to get the hang of it.
这听起来像是家庭作业,是的,是(别人的),我请我的一个正在学习 C# 的朋友借给我一些他的课堂练习来掌握它。
So as the title says: How can I check if a number is a Palindrome?
所以正如标题所说:如何检查数字是否为回文?
I'm not asking for source code (although its very useful), but rather that someone explained how should the code should work, so that it can be applied to many different languages.
我不是在要求源代码(尽管它非常有用),而是有人解释了代码应该如何工作,以便它可以应用于许多不同的语言。
The Solution:
解决方案:
@statikfx searched SO for this and found the solution.
@statikfx 为此搜索了 SO 并找到了解决方案。
n = num;
while (num > 0)
{
dig = num % 10;
rev = rev * 10 + dig;
num = num / 10;
}
// If (n == rev) then num is a palindrome
采纳答案by Jed Smith
I check for palindromes by converting the integer to a string, then reversing the string, then comparing equality. This will be the best approach for you since you're just starting out.
我通过将整数转换为字符串,然后反转字符串,然后比较相等性来检查回文。这将是最适合您的方法,因为您才刚刚开始。
Since you're working in C# and this is homework, I'll use very obscure-looking Python that won't help you:
由于您正在使用 C# 并且这是家庭作业,因此我将使用看起来非常晦涩的 Python,它不会帮助您:
def is_palindrome(i):
s = str(i)
return s[::-1] == s
Convert that to C# and you'll have your answer.
将其转换为 C#,您就会得到答案。
回答by dcp
There are many ways. Probably the simplest is to have 2 indexes, i at beginning and j at end of number. You check to see if a[i] == a[j]. If so, increment i and decrement j. You stop when i > j. When looping if you ever reach a point where a[i] != a[j], then it's not a palindrome.
有很多方法。可能最简单的是有 2 个索引,i 在开头,j 在数字结尾。您检查是否 a[i] == a[j]。如果是,则增加 i 并减少 j。当 i > j 时停止。循环时,如果您到达 a[i] != a[j] 的点,则它不是回文。
回答by ctrlShiftBryan
in theory you want to convert the number to a string. then convet the string to an array of characters and loop the array comparing character (i) with character (array length - i) if the two characters are not equal exit the loop and return false. if it makes it all the way through the loop it is a Palindrome.
理论上你想将数字转换为字符串。然后将字符串转换为字符数组并循环比较字符 (i) 与字符 (数组长度 - i) 的数组,如果两个字符不相等,则退出循环并返回 false。如果它一直通过循环,它就是一个回文。
回答by schnaader
Main idea:
大意:
Input number: 12321
Splitting the digits of the number, put them into an array
=> array [1, 2, 3, 2, 1]
Check if array[x] = array[arr_length - x] for all x = 0..arr_length / 2
If check passed => palindrome
回答by echo
Interesting. I'd probably convert the number to a string, and then write a recursive function to decide whether any given string is a palendrome.
有趣的。我可能会将数字转换为字符串,然后编写一个递归函数来确定任何给定的字符串是否为palendrome。
回答by Moishe Lettvin
Here's some pseudocode:
这是一些伪代码:
function isPalindrome(number) returns boolean
index = 0
while number != 0
array[index] = number mod 10
number = number div 10
index = index + 1
startIndex = 0;
endIndex = index - 1
while startIndex > endIndex
if array[endIndex] != array[startIndex]
return false
endIndex = endIndex - 1
startIndex = startIndex + 1
return true
Note that that's for base 10. Change the two 10s in the first while loop for other bases.
请注意,这是针对基数 10。将第一个 while 循环中的两个 10 更改为其他基数。
回答by Mark Byers
Here's some working code. The first function tests if a number is palidromic by converting it to a string then an IEnumerable and testing if it is equal to its reverse. This is enough to answer your question. The main function simply iterates over the integers testing them one by one.
这是一些工作代码。第一个函数通过将一个数字转换为字符串然后一个 IEnumerable 并测试它是否等于它的反向来测试一个数字是否是回文。这足以回答你的问题。main 函数只是简单地迭代一个整数来测试它们。
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
public static bool IsPalindromic(long l)
{
IEnumerable<char> forwards = l.ToString().ToCharArray();
return forwards.SequenceEqual(forwards.Reverse());
}
public static void Main()
{
long n = 0;
while (true)
{
if (IsPalindromic(n))
Console.WriteLine("" + n);
n++;
}
}
}
Update: Here is a more direct method of generating palindromes. It doesn't test numbers individually, it just generates palindromes directly. It's not really useful for answering your homework, but perhaps you will find this interesting anyway:
更新:这是一种更直接的生成回文的方法。它不单独测试数字,它只是直接生成回文。这对于回答你的家庭作业并不是很有用,但也许你会发现这很有趣:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
public static void Main()
{
bool oddLength = true;
ulong start = 1;
while (true)
{
for (ulong i = start; i < start * 10; ++i)
{
string forwards = i.ToString();
string reverse = new string(forwards.ToCharArray()
.Reverse()
.Skip(oddLength ? 1 : 0)
.ToArray());
Console.WriteLine(forwards + reverse);
}
oddLength = !oddLength;
if (oddLength)
start *= 10;
}
}
}
回答by Zamir
The following function will work for both numbers as well as for strings.
以下函数适用于数字和字符串。
public bool IsPalindrome(string stringToCheck)
{
char[] rev = stringToCheck.Reverse().ToArray();
return (stringToCheck.Equals(new string(rev), StringComparison.OrdinalIgnoreCase));
}
回答by Raz Megrelidze
My solution:
我的解决方案:
bool IsPalindrome(string str)
{
if(str.Length == 1 || str.Length == 0) return true;
return str[0] == str[str.Length-1] && IsPalindrome(str.Substring(1,str.Length-2));
}
回答by Ajai
int n = check_textbox.Text.Length;
int check = Convert.ToInt32(check_textbox.Text);
int m = 0;
double latest=0;
for (int i = n - 1; i>-1; i--)
{
double exp = Math.Pow(10, i);
double rem = check / exp;
string rem_s = rem.ToString().Substring(0, 1);
int ret_rem = Convert.ToInt32(rem_s);
double exp2 = Math.Pow(10, m);
double new_num = ret_rem * exp2;
m=m+1;
latest = latest + new_num;
double my_value = ret_rem * exp;
int myvalue_int = Convert.ToInt32(my_value);
check = check - myvalue_int;
}
int latest_int=Convert.ToInt32(latest);
if (latest_int == Convert.ToInt32(check_textbox.Text))
{
MessageBox.Show("The number is a Palindrome number","SUCCESS",MessageBoxButtons.OK,MessageBoxIcon.Information);
}
else
{
MessageBox.Show("The number is not a Palindrome number","FAILED",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
}