要求:隨機輸入一個數,判斷是否是對稱數(迴文數),要求:不能調用庫函數
其實實現挺簡單的:將數逆置,然後和原來的比較,一旦相等就回文了。而不必像有些考慮的第一個和最後一個比,第二個和倒數第二個比。顯然逆置的方式更科學也更簡單
這也許也是不能使用庫函數的原因吧,因爲大多數語言都有reverse()函數,這樣其實一逆序,比較就完成了。但是其實知道了這個原理,自己寫起來也是很簡單的.
代碼:
package algorithm;
public class Symmetry {
public static void main(String[] args) {
System.out.println(isSymmetry(10101));//直接在代碼中輸入數據,沒有考慮交互問題
}
public static boolean isSymmetry(int n )
{ int temp=0;
int i = n;
while(i>0)//這個while實現了對輸入數字的逆序並保存到temp中
{
temp =temp*10+i%10;
i=i/10;
}
if(n== temp)
{
return true;
}
return false;
}
}
--————————————————————————————————————————————————————————————————————
如果是判斷一個字符串是不是迴文?
1.就是利用reverse()函數,根據不同的語言可能不同,java中String沒有reverse.但是StringBuffer有,所以將String轉爲StringBuffer即可,這個比較簡單
2.自己寫,滿足不調用庫函數----原理同上
package algorithm;
import java.io.*;
public class TestSymmetry {
public static void main(String [] args){
String str=null;
if(args.length==0){ //考慮了命令輸入字符串或者是嚮導模式輸入
System.out.print("Please input string:");
try{
InputStreamReader ir=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(ir);
str=br.readLine();
//System.out.println(str);
}
catch(Exception e){
System.out.println(e);
}
}
else{
str=args[0];
}
if(isSummetry(str)){
System.out.println(str+" 是迴文字符串");
}
else{
System.out.println(str+" 不是迴文字符串");
}
}
public static boolean isSummetry(String str){
String temp="";
boolean flag=false;
for(int i=str.length()-1;i>=0;i--){ //注意是逆序遍歷
temp+=str.charAt(i);//temp最終成爲原始字符串的逆序
}
if(temp.equals(str)){
flag=true;
}
return flag;
}
}