本文转载自:想学习算法?Java笔试手写算法面试12题『含答案』整的明明白白
前言:
我坚信,机会永远属于有准备的人,我们与其羡慕他人的成功,不如从此刻起,积累足够多的的知识和面试经验,为将来进入更好的工作做好充分的准备!
算法面试题+答案
1. 统计一篇英文文章单词个数。
public class WordCounting {
public static void main(String[] args) {
try(FileReader fr = new FileReader("a.txt")) {
int counter = 0;
Boolean state = false;
int currentchar;
while((currentchar= fr.read()) != -1) {
if(currentchar== ' ' || currentchar == 'n'|| currentchar == 't' || currentchar == 'r') {
state = false;
} else if(!state) {
state = true;
counter++;
}
}
System.out.println(counter);
}
catch(Exception e) {
e.printStackTrace();
}
}
}
补充:这个程序可能有很多种写法,这里选择的是Dennis M. Ritchie和Brian W. Kernighan老师在他们不朽的著作《The C Programming Language》中给出的代码,向两位老师致敬。下面的代码也是如此。
2. 输入年月日,计算该日期是这一年的第几天。
public class DayCounting {
public static void main(String[] args) {
int[][] data = {
{31,28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
{31,29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
};
Scanner sc = new Scanner(System.in);
System.out.print("请输入年月日(1980 11 28): ");
int year = sc.nextint();
int month = sc.nextint();
int date = sc.nextint();
int[] daysOfMonth = data[(year %