知識+看到網友提問 無聊就拿來做了

所謂迴文(palindrome)字串就是不論字串從左到右或從右到左都是一樣的字串,
例如:12345654321,3344556554433,ABCDEFGHGFEDCBA皆是迴文.
有一種密碼被設計存放於迴文中,它以阿拉伯數字1~9組成,
字串中兩兩相接的數字之間,後面的數字一定不會大於前面的數字兩倍,密碼則由其中偶數組成,例如:
221151122,則不含密碼,因違反"後面的數字一定不會大於前面的數字兩倍"原則,
423435534324是迴文,且符合規則,故含密碼於其中,密碼為424424.
有一字串陣列如下:
String []password={"1234567654321","234566787666554322","3357533"
,"423435534324","154321123451","123456777654321"}
請依據以上原則撰寫程式擷取密碼,
=======================輸出

迴文  

 

=======================main.java(主程式)

public class main {

public static void main(String[] args) {
String []password={"1234567654321","234566787666554322","3357533"
,"423435534324","154321123451","123456777654321"};
palindrome p=new palindrome();
for(int i=0;i<password.length;i++){
if(p.Judge(password[i])==false){
System.out.println(password[i]+"的密碼為"+p.Password(password[i]));
}else{
System.out.println(password[i]+"不符合條件 無密碼");
}

}
}


}

 

=======================palindrome.java

 


public class palindrome{
public Boolean Judge(String palindrome){
int length=palindrome.length();
Boolean judge1=false;
Boolean judge2=false;
for(int count=0;count<length-1;count++){
if(Integer.parseInt(Character.toString(palindrome.charAt(count+1)))
>Integer.parseInt(Character.toString(palindrome.charAt(count)))*2){//後面數>前一數2倍
judge1=true;
break;
}
}
//後數沒有>前一數的2倍的話換判斷迴文
for(int count=0;count<(length-1)/2;count++){
//如果第N個數不等於第長度-N個數 那就不是迴文
  if(Integer.parseInt(Character.toString(palindrome.charAt(count)))!=
  Integer.parseInt(Character.toString(palindrome.charAt(length-count-1)))){
   judge2=true;
   break;
  }
}
if(judge1==true||judge2==true){
return true;
}else{
return false;
}
}
public String Password(String palindrome){
int length=palindrome.length();
String passw="";

for(int i=0;i<length-1;i+=2)
passw+=Character.toString(palindrome.charAt(i+1));
return passw;
}
}


arrow
arrow
    全站熱搜

    cookiesp 發表在 痞客邦 留言(0) 人氣()