Java經典演算法題_2

來源:互聯網
上載者:User

標籤:src   sel   dex   ext2   finally   bin   標點符號   lis   iss   

1.編寫一個程式,輸入n,求n!(用遞迴的方式實現)。

public static long fac(int n){        if(n<=0) return 0;        else if(n==1)    return 1;        else return n*fac(n-1);    }    public static void main(String [] args) {        System.out.println(fac(6));    }

2.編寫一個程式,有1,2,3,4個數字,能組成多少個互不相同且無重複數位三位元?都是多少?

public static void main(String [] args) {       int i, j, k;       int m=0;       for(i=1;i<=4;i++)          for(j=1;j<=4;j++)            for(k=1;k<=4;k++){               if(i!=j&&k!=j&&i!=k){                 System.out.println(""+i+j+k);                 m++;               }            }        System.out.println("能組成:"+m+"個");}

 3.編寫一個程式,將text1.txt檔案中的單詞與text2.txt檔案中的單詞交替合并到text3.txt檔案中。text1.txt檔案中的單詞用斷行符號符分隔,text2.txt檔案中用斷行符號或空格進行分隔。

import java.io.File;  import java.io.FileReader;  import java.io.FileWriter;    public class text{      public static void main(String[] args) throws Exception{          String[] a = getArrayByFile("text1.txt",new char[]{‘\n‘});          String[] b = getArrayByFile("text2.txt",new char[]{‘\n‘,‘ ‘});                FileWriter c = new FileWriter("text3.txt");         int aIndex=0;        int bIndex=0;                 while(aIndex<a.length){              c.write(a[aIndex++] + "\n");                if(bIndex<b.length)                  c.write(b[bIndex++] + "\n");         }                    while(bIndex<b.length){              c.write(b[bIndex++] +  "\n");         }             c.close();      }       public static String[] getArrayByFile(String filename,char[] seperators) throws Exception{          File f = new File(filename);          FileReader reader = new FileReader(f);          char[] buf = new char[(int)f.length()];          int len = reader.read(buf);          String results = new String(buf,0,len);          String regex = null;          if(seperators.length >1 ){              regex = "" + seperators[0] + "|" + seperators[1];          }else{              regex = "" + seperators[0];          }          return  results.split(regex);      }        }  

4.639172每個位元上的數字都是不同的,且平方後所得數位所有位元都不會出現組成它自身的數字。(639172*639172=408540845584),類似於639172這樣的6位元還有幾個?分別是什嗎?

這題採用的HashMap結構判斷有無重複,也可以採用下題的數組判斷。

public void selectNum(){          for(long n = 100000; n <= 999999;n++){               if(isSelfRepeat(n))                    //有相同的數字,則跳過                continue;               else if(isPingFangRepeat(n*n,n)){    //該數的平方中是否有與該數相同的數字                continue;               }            else{                                //符合條件,則列印                   System.out.println(n);             }           }      }    public boolean isSelfRepeat(long n){        HashMap<Long,String> m=new HashMap<Long,String>();        //儲存的時候判斷有無重複值        while(n!=0){            if(m.containsKey(n%10)){                return true;            }            else{                m.put(n%10,"1");            }            n=n/10;        }        return false;    }    public boolean isPingFangRepeat(long pingfang,long n){        HashMap<Long,String> m=new HashMap<Long,String>();        while(n!=0){            m.put(n%10,"1");            n=n/10;        }        while(pingfang!=0){            if(m.containsKey(pingfang%10)){                return true;            }            pingfang=pingfang/10;        }        return false;    }    public static void main(String args[]){        new test().selectNum();    }

 5.比如,968548+968545=321732732它的答案裡沒有前面兩個數裡的數字,有多少這樣的6位元。

 public void selectNum(){          for(int n = 10; n <= 99;n++){             for(int m = 10; m <= 99;m++){                if(isRepeat(n,m)){                    continue;                }                else{                    System.out.println("組合是"+n+","+m);                }            }        }     }    public boolean isRepeat(int n,int m){        int[] a={0,0,0,0,0,0,0,0,0,0};        int s=n+m;        while(n!=0){            a[n%10]=1;            n=n/10;        }        while(m!=0){            a[m%10]=1;            m=m/10;        }        while(s!=0){            if(a[s%10]==1){                return true;            }            s=s/10;        }        return false;    }    public static void main(String args[]){        new test().selectNum();    }   

6.給定String,求此字串的單詞數量。字串不包括標點,大寫字母。例如 String str="hello world hello hi";單詞數量為3,分別是:hello world hi。

 public static void main(String [] args) {            int count = 0;            String str="hello world hello hi";            String newStr="";            HashMap<String,String> m=new HashMap<String,String>();            String [] a=str.split(" ");            for (int i=0;i<a.length;i++){                if(!m.containsKey(a[i])){                    m.put(a[i],"1");                    count++;                    newStr=newStr+" "+a[i];                }            }            System.out.println("這段短文單詞的個數是:"+count+","+newStr);    }   

7.寫出程式運行結果。

public class Test1 {    private static void test(int[]arr) {        for (int i = 0; i < arr.length; i++) {            try {                if (arr[i] % 2 == 0) {                    throw new NullPointerException();                } else {                    System.out.print(i);                }            }            catch (Exception e) {                System.out.print("a ");            }            finally {                System.out.print("b ");            }        }    }     public static void main(String[]args) {        try {            test(new int[] {0, 1, 2, 3, 4, 5});        } catch (Exception e) {            System.out.print("c ");        }    } }

運行結果:a b 1b a b 3b a b 5b

public class Test1 {    private static void test(int[]arr) {        for (int i = 0; i < arr.length; i++) {            try {                if (arr[i] % 2 == 0) {                    throw new NullPointerException();                } else {                    System.out.print(i);                }            }                        finally {                System.out.print("b ");            }        }    }     public static void main(String[]args) {        try {            test(new int[] {0, 1, 2, 3, 4, 5});        } catch (Exception e) {            System.out.print("c ");        }    } }

運行結果:b c

8.單詞數

 統計一篇文章裡不同單詞的總數。

Input

  有多組資料,每組一行,每組就是一篇小文章。每篇小文章都是由小寫字母和空格組成,沒有標點符號,遇到#時表示輸入結束。

Output

  每組值輸出一個整數,其單獨成行,該整數代表一篇文章裡不同單詞的總數。

Sample Input

you are my friend

#

 

Sample Output

4

public static void main(String [] args) {            List<Integer> countList=new ArrayList<Integer>();            int count;            HashMap<String,String> m;            String str;  //讀取鍵盤輸入的一行(以斷行符號換行為結束輸入)            String[] a;            Scanner in=new Scanner(System.in);                        while( !(str=in.nextLine()).equals("#") ){                a=str.split(" ");                m=new HashMap<String,String>();                count = 0;                for (int i=0;i<a.length;i++){                    if(!m.containsKey(a[i]) && (!a[i].equals(""))){                        m.put(a[i],"1");                        count++;                    }                }                countList.add(count);            }s            for(int c:countList)                     System.out.println(c);    }   

Java經典演算法題_2

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.