Reputation: 27
I am trying to find Palindrome numbers in a given range. Here is my code:
import java.util.Scanner;
import java.util.ArrayList;
public class PalindromeNums{
public static void main(String [] args){
Scanner input = new Scanner(System.in);
int start,end,rem,rev=0,temp;
ArrayList <Integer> palindrome = new ArrayList<>();
System.out.print("Start : ");
start = input.nextInt();
System.out.print("End : ");
end = input.nextInt();
temp = start;
for(int i = start; i <= end; i++){
while(temp != 0){
rem = temp % 10;
rev = rev * 10 + rem;
temp = temp / 10;
}
System.out.println(rev);
if(i == rev){
palindrome.add(i);
}
temp++;
rev = 0;
}
System.out.println(palindrome);
}
}
When I run the code, it's giving the right output for the first integer only. It's not working for other integers in the given range. Any suggestion/solution for this problem? And why it's not working?
Sample output:
Start : 33 End : 55 33 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 [33]
Upvotes: 0
Views: 6319
Reputation: 11
Please try this
import java.util.Scanner;
import java.util.ArrayList;
public class PalindromeNums{
public static void main(String [] args){
Scanner input = new Scanner(System.in);
int start,end,rem,rev=0,temp;
ArrayList <Integer> palindrome = new ArrayList<>();
System.out.print("Start : ");
start = input.nextInt();
System.out.print("End : ");
end = input.nextInt();
// Picking Each Number Of That Range;
for(int i = start; i <= end; i++){
temp =i;
// Checking whether Its Palindrome Or Not
while(temp != 0){
rem = temp % 10;
rev = rev * 10 + rem;
temp = temp / 10;
}
System.out.println(rev);
if(i == rev){
palindrome.add(i);
}
rev = 0;
}
System.out.println(palindrome);
}
}
Upvotes: 1
Reputation: 17900
By the time the loop ends, temp
will be 0 and hence you should not be doing temp++
.
Rather, you need to assign the current number being processed to temp
as the first line of the for loop as
temp = i;
Upvotes: 0
Reputation: 163
Your temp is not incrementing by 1 in the loop.
// temp is initialized to start at first
while(temp != 0){
rem = temp % 10;
rev = rev * 10 + rem;
temp = temp / 10;
}
// at the end of this temp's value is entirely changed.
// above temp is incremented here, ideally temp at the start should be incremented. You can do this by initializing temp as i
temp++;
Upvotes: 1