简体   繁体   English

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

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

I am new to C# and was doing this program as an exercise. 我是C#的新手,正在练习该程序。 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'. 它总是打印“不是回文”。

After some error checking, I realized that the reason why it was doing this is because the last number that gets stored in newnum is just the last digit after being reversed and not the entire number. 经过一些错误检查后,我意识到这样做的原因是因为存储在newnum中的最后一个数字只是反转后的最后一个数字,而不是整个数字。 How can I rectify this?? 我该如何纠正?

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? 我还在网上看了另一个代码示例,但是我不明白的是为什么在while循环中将num转换为布尔类型? Is that just to keep the loop running? 只是为了保持循环运行?

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 :) 谢谢 :)

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). 尝试使用笔和纸(或调试器)逐步进行操作。

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 就像狗屎一样(和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? 您还需要确定负数发生了什么。即-121是一个普通的圆顶吗? This method will say that it isn't... 这个方法会说不是...

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 s1 and s2 and return (s1-s2 == 0) 您还可以对s1s2使用Integers并返回(s1-s2 == 0)

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. 答:您可以将输入保留为字符串并循环遍历,每次迭代检查索引'i'的值和索引'len-i-1'的值是否相等,如果不为false,则在输入末尾返回循环为真。 (the loop should run till i < len/2) (循环应一直运行到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.仅使用计算,还有更多不使用字符串解决方案的方法。

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以确定数字是否被完全拆分。将该数组重新加入并检查输入的数字。

Use the following code: 使用以下代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM