C#如何检查回文号码
我试图解决这个问题:检查数字是否是回文,我知道互联网上有很多示例,但我不明白为什么我的代码不起作用。
using System;
class HelloWorld {
static void Main() {
int number = 122;
int reverse = 0;
while(number!=0){
reverse = (reverse*10) + number%10;
number/=10;
}
Console.Write(reverse);
if(number==reverse){
Console.WriteLine("The number is palindrom");
}
else{
Console.WriteLine("The number isn't palindrom");
}
}
}
我知道我不应该使用 int number = 122; ,但这是我了解代码是否正常的方式。
I tried to solve this problem: check if the number is a palindrome, I know that there are a lot of examples on the Internet, but I don't understand why my code isn't working.
using System;
class HelloWorld {
static void Main() {
int number = 122;
int reverse = 0;
while(number!=0){
reverse = (reverse*10) + number%10;
number/=10;
}
Console.Write(reverse);
if(number==reverse){
Console.WriteLine("The number is palindrom");
}
else{
Console.WriteLine("The number isn't palindrom");
}
}
}
I know that I shouldn't use int number = 122; but this was my way to understand if the code is working.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您应该保存原始号码。在您的情况下,<代码>编号与反向号码进行比较时始终是
0
。You should save your original number. In your case
number
is always0
when comparing to the reverse number.在循环时,您会更改
号码
的值,直到它是0
。所以你总是比较Within you while loop you alter the value of
number
until it's0
. So you always end up comparing魔术发生在循环中:
(反向*10)
“将结果移动”到下一个位置。数字%10
基本上是其余部分。使用号码/= 10
您进入下一个位置,直到什么都没有。使用调试器以了解会发生什么是有用的。
The magic happens in the loop:
(reverse*10)
"shifts" your result to the next place.number%10
is basically the remainder. Withnumber/=10
you go to the next place until there is nothing left.It's useful to use the debugger in order to understand what happens.
将其转换为字符串会更容易:
您不需要将其解析回INT,但是您的示例使用整数。
It would be easier to convert it to a string:
You don't need to parse it back to an int, but your example uses integers.
这是我从可用于多种编程语言的通用假码中遵循的一种方法
This is rather an approach I have followed from general pseudocodes available for multiple programming languages for implementing a palindrome program