面试了一个很厉害的大厂,老师让我写了几道题,在此将其记录。
1.设计一个算法,计算出n阶乘中尾部零的个数
样例 11! = 39916800,因此应该返回 2
挑战 O(logN)的时间复杂度 public static long
count(
long
n) {
long
result =
0
;
long
temp = n /
5
;
while
(temp !=
0
) { result += temp;
temp = temp /
5
;
} return
result;
2. 两个线程交替打印奇数和偶数
(使用两种方法 1.synchronized 2. 阻塞队列 ) public class
ProducerAndConsumer {
public static void
main(String[] args) {
PrintEvenNumber printEvenNumber =
new
PrintEvenNumber();
PrintOddNumber printOddNumber =
new
PrintOddNumber();
printEvenNumber.start();
printOddNumber.start();
}
private static
Integer
count
=
1
;
private static
String
lock
=
"lock"
;
//打印奇数的线程 static class
PrintOddNumber
extends
Thread {
@Override public void
run() { while
(
count
<
100
) { try
{ Thread.
sleep
(
100
);
}
catch
(InterruptedException e) { e.printStackTrace();
}
synchronized
(
lock
) { if
(
isEven
(
count
)) {
//如果是偶数 try
{ lock
.wait();
//需要等待
}
catch
(InterruptedException e) { e.printStackTrace();
} }
//如果能够进行到这里,说明是奇数,可以打印 System.
out
.println(
"奇数:"
+
count
);
count
++;
lock
.notify();
}
}
} }
//打印偶数的线程 static class
PrintEvenNumber
extends
Thread {
@Override public void
run() {
while
(
count
<
100
) {
try
{ Thread.
sleep
(
100
);
}
catch
(InterruptedException e) { e.printStackTrace();
}
synchronized
(
lock
) { if
(!
isEven
(
count
)) {
//如果是奇数 try
{ lock
.wait();
//需要等待
}
catch
(InterruptedException e) { e.printStackTrace();
} } //如果能够进行到这里,说明是偶数,可以打印 System.
out
.println(
"偶数:"
+
count
);
count
++;
lock
.notify();
}
}
} }
//判断是否是偶数的方法 public static boolean
isEven(
int
n) { return
n %
2
==
0
;
}
}
//********阻塞队列方式***********// public class
ProducerAndConsumer {
public static void
main(String[] args) {
PrintEvenNumber printEvenNumber =
new
PrintEvenNumber();
PrintOddNumber printOddNumber =
new
PrintOddNumber();
printEvenNumber.start();
printOddNumber.start();
}
private static
Integer
count
=
1
;
static
BlockingQueue
queue
=
new
ArrayBlockingQueue(
100
);
//打印奇数的线程 static class
PrintOddNumber
extends
Thread {
@Override public void
run() { while
(
count
<
100
) { try
{ Thread.
sleep
(
100
);
}
catch
(InterruptedException e) { e.printStackTrace();
}
try
{ queue
.put(
count
);
}
catch
(InterruptedException e) { e.printStackTrace();
}
//如果能够进行到这里,说明是奇数,可以打印 System.
out
.println(
"奇数:"
+
count
);
count
++;
}
}
}
//打印偶数的线程 static class
PrintEvenNumber
extends
Thread {
@Override public void
run() {
while
(
count
<
100
) {
try
{ Thread.
sleep
(
100
);
}
catch
(InterruptedException e) { e.printStackTrace();
}
try
{ queue
.take();
}
catch
(InterruptedException e) { e.printStackTrace();
} //如果能够进行到这里,说明是偶数,可以打印 System.
out
.println(
"偶数:"
+
count
);
count
++;
}
}
}
//判断是否是偶数的方法 public static boolean
isEven(
int
n) { return
n %
2
==
0
;
}
}
【面试-编程题】
推荐阅读
- InnoDB索引优化
- 面试 - 几道编程题
- 使用Java8新增的Predicate操作集合
- 实现事件监听器对象的几种形式()
- Reference counted Objects (引用计数对象) - 文章翻译
- 处理Blob类型数据()
- java|面试官想问的Java问题,都在这篇文章中了!