Java 查找给定范围内回文数的程序

Java program to find palindrome numbers in given range

我正在尝试查找给定范围内的 回文 数字。这是我的代码:

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);

    }
}

当我 运行 代码时,它只为第一个整数提供正确的输出。它不适用于给定范围内的其他整数。 这个问题有 suggestion/solution 吗?为什么它不起作用?

示例输出:

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]

循环结束时,temp 将为 0,因此您不应该执行 temp++

相反,您需要将当前正在处理的号码分配给temp作为for循环的第一行as

temp = i;

你的温度在循环中没有递增 1。

// 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++;

请试试这个

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);

    }
}