华为笔试题--是否回文

要求:随机输入一个数,判断是否是对称数(回文数),要求:不能调用库函数


其实实现挺简单的:将数逆置,然后和原来的比较,一旦相等就回文了。而不必像有些考虑的第一个和最后一个比,第二个和倒数第二个比。显然逆置的方式更科学也更简单

这也许也是不能使用库函数的原因吧,因为大多数语言都有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;
	   }

}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章