JAVA面试机试题

1.打印“水仙花数”(自己的练习)
所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身。

public class DaffodilNum {

 public static void main(String[] args) {
  for(int i = 1; i < 10; i++) {
   for(int j = 0; j < 10; j++) {
    for(int z = 0; z < 10; z++) {
     int num = i*100 + j*10 +z;
     if(i*i*i + j*j*j + z*z*z == num) {
      System.out.println(num);
     }
    }
   }
  }
 }

}

2.兔子问题(自己的练习)
有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问某个月的兔子总数为多少?

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

public class Hare {

 public static void main(String[] args) {
  BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
  int month = 0;
  try {
   month = Integer.parseInt(reader.readLine());
  } catch (NumberFormatException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  int[] sum = new int[month];
  sum[0] = 1;
  sum[1] = 1;
  for(int i = 2; i < month; i++) {
   sum[i] = sum[i - 1] + sum[i - 2];
  }
        System.out.println(Arrays.toString(sum));
 }

}

3.拆词问题(某公司笔试题)
将一段英文(标点只含有句号和逗号)拆分成单词,并打印把每个词出现的频率按从大到小的顺序打印出来

public class Statistics {

 public static void main(String[] args) {
        String source = "Both sides offered statistics to bolster their arguments." +
          "She's studying statistics at university.";
        Map<String, Integer> map = new HashMap<String, Integer>();
        Set<String> set = new HashSet<String>();
        String temp = "";
        int length = source.length();
        for(int i = 0; i < length; i++) {
         String currentChar = source.substring(i, i+1);
         if(" ".equals(currentChar) || ",".equals(currentChar) || ".".equals(currentChar)) {
          int sizeOld = set.size();
          set.add(temp);
          if(set.size() == sizeOld && map.size() > 0) {
           map.put(temp, map.get(temp) + 1);
          } else {
           map.put(temp, 1);
          }
          temp = "";
         } else {
          temp = temp + currentChar;
         }
        }
        Integer[] values = map.values().toArray(new Integer[set.size()]);
        for(int m = 0; m < values.length; m++) {
         int tempNum = values[m];
         for(int n = m + 1; n < values.length; n++) {
          if(tempNum < values[n]) {
              values[m] = values[n];
              values[n] = tempNum;
             }
         }
        }
       
        System.out.println(Arrays.toString(values));
 }

阅读更多
换一批

没有更多推荐了,返回首页