[英]Can anyone tell me what's going wrong with this code?
這是代碼段。我在這里找不到任何錯誤...任何人都可以幫忙嗎?
while(num != 0) {
rev = rev * 10;
rev = rev + num % 10;
num = num / 10;
}
if (num == rev)
System.out.println("The number is Palindrome");
else
System.out.println("The number is not Palindrome");
此代碼的問題在於,在反轉變量之前,您沒有存儲num
變量的值。 隨着while
開始, num
值開始變化。 你應該做這個:
int temp = num; // storing the original value
int rev = 0; // initial value of rev
// --------
// while loop logic here
// --------
if(temp == rev) // change your condition here
// and you're good to go
首先,您需要初始化rev
的值,因為它是一個局部變量。 然后,您需要將num
的值存儲在一個臨時值中,以便將其與您的rev
進行比較。 這是一段包含您的代碼的方法:
public void isPalindrome(int num) {
int rev = 0;
int temp = num;
while(num!=0)
{
rev=rev*10;
rev= rev+num%10;
num=num/10;
}
if(temp==rev)
System.out.println("The number is Palindrome");
else
System.out.println("The number is not Palindrome");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.