Java手写算法面试题

本文提供了Java编程中常见的算法面试题,包括统计英文文章单词数、日期计算、回文素数查找、全排列、最大子数组和、字符串倒转、素数分解、台阶问题、字母唯一性检查、有序数组去重、多数元素查找以及字符串字节长度计算等,涵盖了动态规划、递归等多种算法思想。
摘要由CSDN通过智能技术生成

java笔试手写算法面试题大全含答案

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 % 4 == 0 && year % 100 != 0 || year % 400 == 0)?1 : 0];
int sum = 0;
for(int i = 0; i < month -1; i++) {
sum += daysOfMonth[i];
}
sum += date;
System.out.println(sum);
sc.close();
}
}


3、回文素数:所谓回文数就是顺着读和倒着读一样的数(例如:11,121,1991…),回文素数就是既是回文数

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值