Java中使用while和for循环的回文数程序
什么是回文数?
一个回文数 是一个在反转时保持不变的数字。例如,131。当它的数字颠倒时,它仍然是相同的数字。回文数在垂直轴上具有反射对称性。指字母颠倒后拼写相同的单词。
Java 中的回文数示例
121, 393, 34043, 111, 555, 48084
回文数示例
LOL, MADAM
回文数算法
下面是Java中的回文数算法逻辑:
- 获取需要检查是否为回文的输入数字
- 将数字复制到一个临时变量中并反转它。
- 比较倒序数和原数。
- 如果它们相同,则数字为“回文数”
- 其他数字不是“回文数”
如何判断输入的数是否为回文数
下面是一个带有while循环的Java回文程序
package com.guru99; public class PalindromeNum { public static void main(String[] args) { int lastDigit,sum=0,a; int inputNumber=171; //It is the number to be checked for palindrome a=inputNumber; // Code to reverse a number while(a>0) { System.out.println("Input Number "+a); lastDigit=a%10; //getting remainder System.out.println("Last Digit "+lastDigit); System.out.println("Digit "+lastDigit+ " was added to sum "+(sum*10)); sum=(sum*10)+lastDigit; a=a/10; } // if given number equal to sum than number is palindrome otherwise not palindrome if(sum==inputNumber) System.out.println("Number is palindrome "); else System.out.println("Number is not palindrome"); } }
代码输出:
Input Number 171 Last Digit 1 Digit 1 was added to sum 0 Input Number 17 Last Digit 7 Digit 7 was added to sum 10 Input Number 1 Last Digit 1 Digit 1 was added to sum 170 Number is palindrome
使用 for 循环检查回文的程序
下面是一个使用 for 循环的回文 Java 程序
package com.guru99; public class PalindromeNum { public static void main(String[] args) { int lastDigit,sum=0,a; int inputNumber=185; //It is the number to be checked for palindrome a=inputNumber; // Code to reverse a number for( ;a != 0; a /= 10 ) { System.out.println("Input Number "+a); lastDigit=a%10; //getting remainder System.out.println("Last Digit "+lastDigit); System.out.println("Digit "+lastDigit+ " was added to sum "+(sum*10)); sum=(sum*10)+lastDigit; a=a/10; } // if given number equal to sum than number is palindrome otherwise not palindrome if(sum==inputNumber) System.out.println("Number is palindrome "); else System.out.println("Number is not palindrome"); } }
代码输出:
Input Number 185 Last Digit 5 Digit 5 was added to sum 0 Input Number 1 Last Digit 1 Digit 1 was added to sum 50 Number is not palindrome
java