目录
Java 中回文背后的逻辑
如何使用各种方法测试回文?
1.使用for循环检查回文数的程序
2.使用 While 循环检查回文数的程序
3.使用库方法检查回文数的程序(对于字符串)
结论
首页 Java java教程 Java 中的回文

Java 中的回文

Aug 30, 2024 pm 04:26 PM
java

如果字符串或数字颠倒后仍保持不变,则称其为回文。例如,“MADAM”是一个回文字符串,因为即使颠倒过来也会拼写为“MADAM”。但在“LUCKY”的情况下,该字符串不是回文,因为反转后它是“YKCUL”。一些回文数是 365563、48984、12321、171、88、90009、343,一些回文字符串是 MADAM、MALAYALAM、LOL、DAD、MOM、C++&++C 等接下来让我们看看回文的逻辑和实现。在本主题中,我们将学习 Java 中的回文。

开始您的免费软件开发课程

网络开发、编程语言、软件测试及其他

Java 中回文背后的逻辑

为了检查一个数字是否是回文数,可以使用以下算法。

  • 输入一个字符串或数字,需要检查它是否是回文。

例如,让我们输入数字 353。

  • 获取输入数字并将其复制到临时变量

353-> temp

  • 使用 for、while 或您选择的任何方法反转它。

Reversednumber: rev=353

  • 比较输入的数字和反转的数字。

如果它们相同,则该数字被称为回文数。

否则,该数字不是回文数。

If(inputnum==rev)
{ then palindrome }
Else not palindrome

如何使用各种方法测试回文?

有几种方法可以检查给定的输入数字是否是回文。

  • For 循环
  • While 循环
  • 库方法(用于字符串)

让我们详细研究每一个:

1.使用for循环检查回文数的程序

代码:

//Java program to check whether a String is a Palindrome or not using For Loop
import java.util.*;
public class PalindromeNumberExample {
//main method
public static void main(String[] args) {
int r=0 ; //reversed Integer
int rem, num; //remainder and original number
Scanner s = new Scanner(System.in);
System.out.print("Enter number that has to be checked:");
num = s.nextInt();
//Store the number in a temporary variable
int temp = num;
//loop to find the reverse of a number
for( ;num != 0; num /= 10 )
{
rem = num % 10; // find the modulus of the number when divided by 10
r = r * 10 + rem;
}
//check whether the original and reversed numbers are equal
if (temp == r)
{
System.out.println(temp + " is input number");
System.out.println(r + " is the reversed number");
System.out.println("Since they are equal " + temp + " is a palindrome number");
}
else
{
System.out.println(temp + " is input number");
System.out.println(r + " is the reversed number");
System.out.println("Since they are not equal " + temp + " is not a palindrome number");
}
}
}

输出 1:

Java 中的回文

这里,由于353颠倒后是一样的,所以被认为是回文。

输出 2:

Java 中的回文

这里,由于 234 颠倒后仍然不一样,因此不被视为回文。

2.使用 While 循环检查回文数的程序

代码:

//Java program to check whether a number is a Palindrome or not using While Loop
import java.util.*;
public class PalindromeNumberExample {
public static void main(String[] args) {
int r=0, rem, num;
Scanner s = new Scanner(System.in);
System.out.print("Enter number that has to be checked:");
num = s.nextInt();
//Store the number in a temporary variable
int temp = num;
//loop to find the reverse of a number
while( num != 0 )
{
rem= num % 10;
r= r * 10 + rem;
num=num/10;
}
//check whether the original and reversed numbers are equal
if (temp == r)
{
System.out.println(temp + " is input number");
System.out.println(r + " is the reversed number");
System.out.println("Since they are equal " + temp + " is a palindrome number");
}
else
{
System.out.println(temp + " is input number");
System.out.println(r + " is the reversed number");
System.out.println("Since they are not equal " + temp + " is not a palindrome number");
}
}
}

输出 1:

Java 中的回文

输出 2:

Java 中的回文

3.使用库方法检查回文数的程序(对于字符串)

代码:

//Java program to check whether a String is a Palindrome or not using Library method
import java.util.*;
public class PalindromeNumberExample {
//Function to check whether the string is palindrome or not
public static void PalindromeCheck(String str)
{
// reverse the input String
String rev = new StringBuffer(str).reverse().toString();
// checks whether the string is palindrome or not
if (str.equals(rev))
{
System.out.println("input string is :" + str);
System.out.println("Reversed string is :" + rev);
System.out.println("Since the input and reversed string are equal, "+ str +" is a palindrome");
}
else
{
System.out.println("input string is :" + str);
System.out.println("Reversed string is :" + rev);
System.out.println("Since the input and reversed string are not equal, "+ str +" is not a palindrome");
}
}
public static void main (String[] args)
{
PalindromeCheck("MALAYALAM");
}
}

输出:

Java 中的回文

这里,输入字符串是在程序本身中传递的。

要检查字符串是否是回文,还可以使用以下程序。

代码:

//Java program to check whether a String is a Palindrome or not
import java.util.*;
public class PalindromeNumberExample {
public static void main(String args[])
{
String st, rev = "";
Scanner sc = new Scanner(System.in);
System.out.println("Enter the string that has to be checked:");
st = sc.nextLine();
int len = st.length(); //length of the string
for ( int i = len- 1; i >= 0; i-- )
rev = rev + st.charAt(i);
if (st.equals(rev))
{
System.out.println("input string is :" + st);
System.out.println("Reversed string is :" + rev);
System.out.println("Since the input and reversed string are equal, "+ st +" is a palindrome");
}
else
{
System.out.println("input string is :" + st);
System.out.println("Reversed string is :" + rev);
System.out.println("Since the input and reversed string are not equal, "+ st +" is not a palindrome");
}
}
}

输出:

Java 中的回文

结论

如果一个数字即使颠倒也保持不变,则称为回文数。回文也可以在字符串中检查。回文数和字符串有 MOM、MALAYALAM、DAD、LOL、232、1331 等。本文档涵盖了回文数的几个方面,如算法、方法、实现等。

以上是Java 中的回文的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

Rimworld Odyssey温度指南和Gravtech
1 个月前 By Jack chen
初学者的Rimworld指南:奥德赛
1 个月前 By Jack chen
PHP变量范围解释了
4 周前 By 百草
撰写PHP评论的提示
3 周前 By 百草
在PHP中评论代码
3 周前 By 百草

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

热门话题

Laravel 教程
1604
29
PHP教程
1509
276
Edge PDF查看器不起作用 Edge PDF查看器不起作用 Aug 07, 2025 pm 04:36 PM

testthepdfinanotherapptoderineiftheissueiswiththefileoredge.2.enablethebuilt inpdfviewerbyTurningOff“ eflblyopenpenpenpenpenpdffilesexternally”和“ downloadpdffiles” inedgesettings.3.clearbrowsingdatainclorwearbrowsingdataincludingcookiesandcachedcachedfileresteroresoreloresorelorsolesoresolesoresolvereresoreorsolvereresoreolversorelesoresolvererverenn

如何在Java中实现简单的TCP客户端? 如何在Java中实现简单的TCP客户端? Aug 08, 2025 pm 03:56 PM

Importjava.ioandjava.net.SocketforI/Oandsocketcommunication.2.CreateaSocketobjecttoconnecttotheserverusinghostnameandport.3.UsePrintWritertosenddataviaoutputstreamandBufferedReadertoreadserverresponsesfrominputstream.4.Usetry-with-resourcestoautomati

用Docker将Java应用程序部署到Kubernetes 用Docker将Java应用程序部署到Kubernetes Aug 08, 2025 pm 02:45 PM

容器化Java应用:创建Dockerfile,使用基础镜像如eclipse-temurin:17-jre-alpine,复制JAR文件并定义启动命令,通过dockerbuild构建镜像并用dockerrun测试本地运行。2.推送镜像到容器注册表:使用dockertag标记镜像并推送到DockerHub等注册表,需先登录dockerlogin。3.部署到Kubernetes:编写deployment.yaml定义Deployment,设置副本数、容器镜像和资源限制,编写service.yaml创建

VS代码快捷方式专注于Explorer面板 VS代码快捷方式专注于Explorer面板 Aug 08, 2025 am 04:00 AM

VSCode中可通过快捷键快速切换面板与编辑区。要跳转至左侧资源管理器面板,使用Ctrl Shift E(Windows/Linux)或Cmd Shift E(Mac);返回编辑区可用Ctrl `或Esc或Ctrl 1~9。相比鼠标操作,键盘快捷键更高效且不打断编码节奏。其他技巧包括:Ctrl KCtrl E聚焦搜索框,F2重命名文件,Delete删除文件,Enter打开文件,方向键展开/收起文件夹。

修复:Windows Update无法安装 修复:Windows Update无法安装 Aug 08, 2025 pm 04:16 PM

runthewindowsupdatetrubloubleshooterviaSettings>更新&安全> is esseShootsoAtomationfixCommonissues.2.ResetWindowSupDateComponentsByStoppingRealatedServices,RenamingTheSoftWaredWaredWaredSoftwaredSistribution andCatroot2Folders,intrestrestartingthertingthertingtherserviceSteStoceTocle

如何在Java中使用一个时循环 如何在Java中使用一个时循环 Aug 08, 2025 pm 04:04 PM

AwhileloopinJavarepeatedlyexecutescodeaslongastheconditionistrue;2.Initializeacontrolvariablebeforetheloop;3.Definetheloopconditionusingabooleanexpression;4.Updatethecontrolvariableinsidethelooptopreventinfinitelooping;5.Useexampleslikeprintingnumber

如何使用Mockito在Java中嘲笑? 如何使用Mockito在Java中嘲笑? Aug 07, 2025 am 06:32 AM

要有效使用Mockito进行Java单元测试,首先需添加Mockito依赖,Maven项目在pom.xml中加入mockito-core依赖,Gradle项目添加testImplementation'org.mockito:mockito-core:5.7.0';接着通过@Mock注解(配合@ExtendWith(MockitoExtension.class))或mock()方法创建模拟对象;然后使用when(...).thenReturn(...)等方式对模拟对象的方法行为进行存根,也可配置异

Java对象的序列化过程是什么? Java对象的序列化过程是什么? Aug 08, 2025 pm 04:03 PM

JavaserializationConvertSanObject'SstateIntoAbyTeSteAmForStorageorTransermission,andDeserializationReconstructstheObjectStheObjectFromThstream.1.toenableserialization,aclassMustimustimplementTheSerializableizableface.2.UseObjectObjectObjectObjectOutputputputputputtreamToserialializeanobectizeanobectementeabectenobexpent,savin

See all articles