我试图在Stack Overflow上使用一些代码,但是当我使用一些代码时,我没有得到想要的答案,现在这是我的代码:
public class JavaApplication7 {
public static void main(String[] args) {
boolean answer = rev(1221);
if(answer == true) System.out.println("true");
else System.out.println("false");
}
static boolean rev(int number){
int reverse = 0, remain;
int num = number;
while(number > 0){
remain = number % 10;
reverse = (reverse * 10) + remain;
num = num / 10;
}
return number == reverse;
}
}
我想检查回文是否等于原始整数。
您的转速功能应如下。
reversedInteger = 0, remainder, originalInteger;
originalInteger = num;
while( num != 0 )
{
remainder = num % 10;
reversedInteger = reversedInteger * 10 + remainder;
num /= 10;
}
您有两个与num
(您要修改的本地副本)和number
(您未修改的参数)混淆有关的错误。我将final
明确表示该值是常数。然后一致使用num
。我还将简化代码。喜欢,
static boolean rev(final int number) {
int reverse = 0;
int num = number;
while (num > 0) {
reverse *= 10;
reverse += num % 10;
num /= 10;
}
return number == reverse;
}
[类似地,在main
中,使用if
打印true
或false
是没有意义的(如果要使用if (answer)
,则不要添加不必要的== true
)。但是,我希望,
public static void main(String[] args) {
boolean answer = rev(1221);
System.out.println(answer);
}
哪个输出
true
static boolean rev(int number){
int reverse = 0;
int num = number;
while(number > 0){
reverse = reverse * 10 + number % 10;
number /= 10;
}
return reverse == num;
}