在C#中找出一个数字是否是回文

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16519325/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:12:53  来源:igfitidea点击:

Finding out whether a number is a palindrome or not in C#

c#

提问by user1440323

I am new to C# and was doing this program as an exercise. I have managed to get my program to print the reversed number of the input given by the user, but when I move onto checking whether it is a palindrome or not, it does not calculate the answer correctly. It always prints 'not a palindrome'.

我是 C# 新手,正在做这个程序作为练习。我已经设法让我的程序打印出用户给出的输入的倒数,但是当我继续检查它是否是回文时,它没有正确计算答案。它总是打印“不是回文”。

After some error checking, I realized that the reason why it was doing this is because the last number that gets stored in newnumis just the last digit after being reversed and not the entire number. How can I rectify this??

经过一些错误检查后,我意识到这样做的原因是因为存储newnum的最后一个数字只是反转后的最后一位数字,而不是整个数字。我怎样才能纠正这个?

My Code

我的代码

        int i, remainder = 0, newnum = 0;
        Console.WriteLine("Enter a Number: ");
        int uinput = Convert.ToInt32((Console.ReadLine()));
        for (i = uinput; i > 0; i = (i / 10))
        {
            remainder = i % 10;
            Console.Write(remainder);

            newnum = remainder;

        }


        if (newnum == uinput)
        {
            Console.WriteLine("The Number {0} is a palindrome", uinput);
        }
        else
        {
            Console.WriteLine("Number is not a palidrome");
        }
        Console.WriteLine(uinput);
        Console.WriteLine(newnum);
        Console.ReadKey();
    }

I also looked online at another code example, but the thing I don't understand in that is why num is being converted to boolean type in the while loop? Is that just to keep the loop running?

我还在网上查看了另一个代码示例,但我不明白的是为什么 num 在 while 循环中被转换为布尔类型?那只是为了保持循环运行吗?

The Code reffered to above

上面提到的守则

        int num, rem, sum = 0, temp;
        //clrscr();
        Console.WriteLine("\n >>>> To Find a Number is Palindrome or not <<<< ");
        Console.Write("\n Enter a number: ");
        num = Convert.ToInt32(Console.ReadLine());
        temp = num;
        while (Convert.ToBoolean(num))
        {
            rem = num % 10;  //for getting remainder by dividing with 10
            num = num / 10; //for getting quotient by dividing with 10
            sum = sum * 10 + rem; /*multiplying the sum with 10 and adding
                       remainder*/
        }
        Console.WriteLine("\n The Reversed Number is: {0} \n", sum);
        if (temp == sum) //checking whether the reversed number is equal to entered number
        {
            Console.WriteLine("\n Number is Palindrome \n\n");
        }
        else
        {
            Console.WriteLine("\n Number is not a palindrome \n\n");
        }
        Console.ReadLine();

Any sort of help is much appreciated!! Thank You :)

任何形式的帮助都非常感谢!!谢谢你 :)

采纳答案by Paolo Falabella

I'm not sure what you're asking, since the second snippet of code you found online should fix your issue. Your code works, if you just change the line

我不确定您在问什么,因为您在网上找到的第二段代码应该可以解决您的问题。你的代码有效,如果你只是改变行

newnum = remainder;

to

newnum = (newnum*10) + remainder;

The issue in your case is not the condition you used in the for loop, it's just that you're overwriting newnum with the remainder every time, so newnum is only storing the last reminder that was calculated in the loop, "forgetting" all the others it had calculated before.

你的问题不是你在 for 循环中使用的条件,只是你每次都用余数覆盖 newnum,所以 newnum 只存储在循环中计算的最后一个提醒,“忘记”所有其他它之前计算过的。

To reverse the number, every time you enter the loop, you should add the last remainder you've found to the right of newnum, which is effectively equivalent to multiplying everything by 10 and adding remainder.

要反转数字,每次进入循环时,您应该将找到的最后一个余数添加到 newnum 的右侧,这实际上等效于将所有内容乘以 10 并添加余数。

Try to follow it step by step with pen and paper (or with a debugger).

尝试用笔和纸(或使用调试器)一步一步地遵循它。

回答by El Ronnoco

public bool isPalindome(int num)
{
  string sNum = num.ToString();
  for (int i = 0; i<sNum.Length; i++) 
      if (sNum[i] != sNum[sNum.Length-1-i]) return false;

  return true;
}

I think that will do it... Untested!!

我认为这会做到......未经测试!!

As dognose (and Eren) correctly assert you only need to go halfway through

由于dognose(和Eren)正确断言,您只需要进行一半

public bool isPalindome(int num)
{
  string sNum = num.ToString();
  for (int i = 0; i < sNum.Length/2; i++) 
      if (sNum[i] != sNum[sNum.Length-1-i]) return false;

  return true;
}

You will also need to decide what happend to negative numbers.. ie is -121 a plaindome? This method will say that it isn't...

您还需要确定负数发生了什么。即 -121 是平顶吗?这种方法会说它不是...

回答by Orel Eraki

You have many ways of accomplish this exercise.

你有很多方法来完成这个练习。

A. You can leave the input as string and loop it over, every iteration to check if the value of index 'i' and value of index 'len-i-1' are equals, if not false, otherwise return at the end of the loop true. (the loop should run till i < len/2)

A. 可以将输入保留为字符串并循环遍历,每次迭代检查索引 'i' 的值和索引 'len-i-1' 的值是否相等,如果不相等,否则在结束时返回循环是真的。(循环应该运行到 i < len/2)

B. You can create a new string and insert the text from end to start and then compare if the original string and result string are equals.

B. 您可以创建一个新字符串并从头到尾插入文本,然后比较原始字符串和结果字符串是否相等。

C. there are much more ways without using the string solutions, just with calculation..

C. 有更多方法不使用字符串解决方案,只需计算即可..

回答by dognose

Easiest way:

最简单的方法:

public static Boolean isPalindrom(Int32 number){
  char[] n1 = number.ToString().ToCharArray();
  char[] n2 = number.ToString().ToCharArray();
  Array.Reverse(n2);

  String s1 = new String(n1);
  String s2 = new String(n2);

  return (s1 == s2);
}

https://dotnetfiddle.net/HQduT5

https://dotnetfiddle.net/HQduT5

you could also use Integers for s1and s2and return (s1-s2 == 0)

你也可以使用整数 for s1ands2并返回(s1-s2 == 0)

回答by Ultima

int x;
cin<<x; //input the number
int ar[];
int i=0;
temp2=0;
while(x/10 != 0)
    {
        int temp=x%10;
        ar[i]=temp;
        x=x/10;
        i++;
    }
for(int j=0, j<i,j++)
    {
        temp2=temp2*10+ar[j];
    }
if(temp2==x){cout<<"palindrome"}
    else {"not palindrome"}

ok here is the logic:

好的,这是逻辑:

we first input the number x(it can be of any length)..Next we split the number into array..the condition to do this is tha we check for the qoutient to decide whether the number is fully split..next we take the array and rejoin it and check with the input number..

我们首先输入数字 x(它可以是任意长度)。接下来我们将数字拆分成数组..这样做的条件是我们检查 qoutient 以确定数字是否完全拆分..接下来我们取数组并重新加入它并检查输入数字..

回答by user3198059

Use the following code:

使用以下代码:

public boolean isPalindrom(Integer number)
{ 
   return number.Equals(int.Parse(String.Join("", String.Join("", number.ToString().ToCharArray().Reverse().ToArray()))));
}