究极 终极:如何判断输入的一个五位数是否是回文数如“12321”

来源:百度文库 编辑:高校问答 时间:2024/04/26 09:27:35
在键盘上输入一五位数,判断它是否是五位数,如“12321”它是回文数!

将五位数拆开(用字符方式拆或用算数方式拆都行),判断:如果第1位和第5位相等,且第2位和第4位相等,就是回文数。

不同语言做法不同,但思路想同!
用循环判断首字和尾字是不是相同
i=0 字首
n= x 字尾
for a=0 to n
if n-a=i+a
renturn
next a

用两个指针,一个指向头,一个尾,进行比较就行了

in java:
//Palindrome.java

import java.awt.* ;
import java.awt.event.* ;
import javax.swing.* ;

public class Palindrome extends JFrame implements ActionListener {
private int start ;
private int end ;

JLabel tip = new JLabel("Enter a word:") ;
JTextField tf_word = new JTextField(10) ;
JButton ok = new JButton("OK") ;
JButton clear = new JButton("Clear") ;
JButton exit = new JButton("Exit") ;

JPanel pane = new JPanel() ;

public Palindrome() {
super("Palindrome V_1.0") ;
try {
inits() ;
} catch(Exception e) {
e.printStackTrace() ;
}
}

public static void main(String[] args) {
Palindrome p = new Palindrome() ;
p.setResizable(false) ;
}

public void inits() {
setBounds(300,300,250,100) ;

ok.addActionListener(this) ;
clear.addActionListener(this) ;
exit.addActionListener(this) ;

pane.add(tip) ;
pane.add(tf_word) ;
pane.add(ok) ;
pane.add(clear) ;
pane.add(exit) ;

setContentPane(pane) ;
setVisible(true) ;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ;
}

public void actionPerformed(ActionEvent e) {
String sCommand = e.getActionCommand() ;

if(sCommand.equals("OK")) {
//check() ;
compare() ;
}
else if(sCommand.equals("Clear")) {
clear() ;
}
else if(sCommand.equals("Exit")) {
System.exit(0) ;
}
}

public void clear() {
System.out.println("Clear button is clicked") ;
tf_word.setText("") ;
}

public boolean compare() {
for(start=0; start<(tf_word.getText().length()-1)/2; start++) {
for(end = tf_word.getText().length()-1; end>0; end--) {
if(tf_word.getText().charAt(start) == tf_word.getText().charAt(end)) {
System.out.print("this word " + tf_word.getText() + " is a palindrome") ;
System.out.println('\n') ;
return true ;
}
else{
System.out.print("this word " + tf_word.getText() + " is not a palindrome") ;
System.out.println('\n') ;
return false ;
}
}
}
return true ;
}

/*public void check() {
if(tf_word.getText() ==" ") {
JOptionPane.showMessageDialog(null, "can not use blank word!") ;
}
}*/
}