我正在尝试在给定范围内找到 Palindrome 数字。这是我的代码:
methods: {
getSelectedItem: function(selected) {
console.log(selected);
},
exportXML: function(selected) {
console.log(selected);
this.$http.get(
'http://localhost:8080/api/exports/' + selected,
});
}
}
当我运行代码时,它只为第一个整数提供正确的输出。它不适用于给定范围内的其他整数。 对此问题的任何建议/解决方案?为什么它不工作?
示例输出:
开始时间:33结束:55 33 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 [33]
答案 0 :(得分:1)
你的temp在循环中没有递增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++;
答案 1 :(得分:1)
请试试这个
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);
}
}
答案 2 :(得分:0)
当循环结束时,temp
将为0,因此您不应该temp++
。
相反,您需要将当前正在处理的号码指定为temp
作为 循环的第一行
temp = i;