Java面试经典题汇总与详细解析
1. 计算某年某月某日是星期几
在计算机科学中,确定日期对应的星期是常见需求,尤其是涉及日期处理的应用开发时。面试中通常会要求编写代码来计算特定日期的星期。
代码解析:
- 闰年判断:通过
leapyear
函数检查年份是否为闰年。
int leapyear(int y) {
if (y % 4 == 0 && y 0 != 0 || y @0 == 0)
return 1;
else
return 0;
}
- 计算月份天数:通过
day_calculate
函数获取某月天数,注意二月需按闰年判断。
int day_calculate(int y, int m) {
int day[12] = {31, 0, 31, 31, 30, 31};
day[1] = 28 + leapyear(y);
return day[m - 1];
}
- 计算星期几:
dow
函数用于获取指定日期为星期几。
int dow(int y, int m) {
int y1 = 1900, m1 = 1, d1 = 1;
long days = 1;
while (y1 != y || m1 != m) {
days++;
d1++;
if (d1 > day_calculate(y1, m1)) {
m1++;
d1 = 1;
}
if (m1 > 12) {
y1++;
m1 = 1;
}
}
return days % 7;
}
2. 查找字符串中出现次数最多的字符及统计
面试中要求编写代码找到字符串中出现次数最多的字符,以下代码先对字符串进行排序,然后逐字符统计。
public static void main(String[] args) {
String s = "1456drtgsegsdfgjygjtyujytutyur34324343fgy";
StringBuffer sb = new StringBuffer(s);
bubbleSort(sb);
char maxChar = sb.charAt(0), prevChar = sb.charAt(0);
int maxCount = 0, currCount = 0;
for (int i = 0; i < sb xss=removed xss=removed> maxCount) {
maxCount = currCount;
maxChar = prevChar;
}
currCount = 1;
prevChar = currChar;
}
}
System.out.println(maxChar);
System.out.println(maxCount);
}
3. Java 调用 C++ 代码
在性能敏感的场景中,Java 可以通过 JNI 调用 C++。
- 定义 JNI 方法:在 Java 中声明
native
方法,由 C++ 实现。 - 编写 C++ 代码:实现 native 方法并打包为动态库。
- 加载和调用 C++ 库:使用 Java 的
System.loadLibrary
调用。
4. 截取包含中文的字符串
在处理包含中文的字符串时需避免截取半个汉字。
代码解析:
public String substring(String input, int n) {
byte[] bytes = input.getBytes();
byte[] data = new byte[n];
int x = 0, y = 0;
while (x < n xss=removed> 1) {
if (x >= n - 1) break;
data[x] = bytes[x];
data[x + 1] = bytes[x + 1];
x += 2;
y++;
} else {
data[x] = bytes[x];
x++;
y++;
}
}
return new String(data, 0, x);
}
以上知识点包括从基础算法到复杂的编码技巧,对于 Java 开发者来说,这些都很重要且常见。
39.5KB
文件大小:
评论区