面试-java算法题

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);
    }   
时间: 2024-08-14 08:39:27

面试-java算法题的相关文章

趣味Java算法题(附答案)

[程序1] 题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少? //这是一个菲波拉契数列问题 public class lianxi01 { public static void main(String[] args) { System.out.println("第1个月的兔子对数:    1"); System.out.println("第2个月的兔子对数:    1"

C++笔试面试(算法题集三)

1>    编写strcpy函数,已知函数原型char*strcpy(char* strDest,char* strSrc) ANSWER: Chat* strcpy(char* strDest,char* strSrc) { If(strSrc==NULL)  return NULL; Char*ch1=strSrc,*ch2=strDest; While(*ch1!='\0') { *ch2++=*ch1++; } *ch2='\0'; Return strDest; } 2>    用递

java面试 - 经典算法题

题目一: public class testClockwiseOutput { //顺时针打印一个矩阵 @Test public void test(){ int[][] num = new int[100][100]; int n = 4; int count =1; for(int i=0;i<n;i++){ for(int j =0;j<n;j++){ num[i][j]=count++; } } output(num,0,n-1); } public void output(int[]

几个面试经典算法题Java解答

题目一: public class testClockwiseOutput { //顺时针打印一个矩阵 @Test public void test(){ int[][] num = new int[100][100]; int n = 4; int count =1; for(int i=0;i<n;i++){ for(int j =0;j<n;j++){ num[i][j]=count++; } } output(num,0,n-1); } public void output(int[]

25道经典Java算法题

即使做web开发,也会遇到各种各种需要解决的算法问题,本文节选部分经典练手算法,并提供相关参考答案,希望对你有所帮助[程序1]题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少? //这是一个菲波拉契数列问题 public class test01 { public static void main(String[] args) { int f1=1,f2=1,f; int M=30; System.

程序员面试金典算法题

空格替换 题目描述 请编写一个方法,将字符串中的空格全部替换为"%20".假定该字符串有足够的空间存放新增的字符,并且知道字符串的真实长度(小于等于1000),同时保证字符串由大小写的英文字母组成. 给定一个string iniString 为原始的串,以及串的长度 int len, 返回替换后的string. 测试样例: "Mr John Smith",13 返回:"Mr%20John%20Smith" "Hello World&qu

【JAVA算法题】职业抢劫

题目 /*You are a professional robber planning to rob houses along a street. * Each house has a certain amount of money stashed, * the only constraint stopping you from robbing each of them is that * adjacent houses have security system connected and *

面试基础算法题

---恢复内容开始--- 动态规划求数组中最长的上升序列(LongestIncreasingSubsequence)的个数,复杂度为O(n^2). 例如:数组int  arr[] = {7,3,5,9,4,6,8,10},最长上升序列应该为3,5,6,8,10或3,4,6,8,10 ,最终答案应该为5: dp[i]表示数组中以下标i结尾的最长上升序列的个数,则原问题就转换为了求所有dp[i](0<=i<len)中的最大值: 而每一个dp[i]又是以下标i结尾的所有序列中最长上升序列的个数. i

网上的一些java算法题的个人练习笔记

1 package com.test; 2 3 import java.io.BufferedReader; 4 import java.io.InputStreamReader; 5 import java.util.Arrays; 6 7 import org.junit.Test; 8 9 public class Test01 { 10 11 /** 12 * 键盘输入一行字符,分别统计出其中英文字母.空格.数字和其它字符的个数. 13 * @throws Exception 14 */