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

Wesley13
• 阅读 453

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…),回文素数就是既是回文数又是素数(只能被1和自身整除的数)的数。编程找出11~9999之间的回文素数。
public class PalindromicPrimeNumber {
public static void main(String[] args) {
for(int i = 11; i <= 9999; i++) {
if(isPrime(i) && isPalindromic(i)) {
System.out.println(i);
}
}
}
public static boolean isPrime(int n) {
for(int i = 2; i <= Math.sqrt(n); i++) {
if(n % i == 0) {
return false;
}
}
return true;
}
public static boolean isPalindromic(int n) {
int temp = n;
int sum = 0;
while(temp > 0) {
sum= sum * 10 + temp % 10;
temp/= 10;
}
return sum == n;
}
}

4.全排列:给出五个数字12345的所有排列。
public class FullPermutation {
public static void perm(int[] list) {
perm(list,0);
}
private static void perm(int[] list, int k) {
if (k == list.length) {
for (int i = 0; i < list.length; i++) {
System.out.print(list[i]);
}
System.out.println();
}else{
for (int i = k; i < list.length; i++) {
swap(list, k, i);
perm(list, k + 1);
swap(list, k, i);
}
}
}
private static void swap(int[] list, int pos1, int pos2) {
int temp = list[pos1];
list[pos1] = list[pos2];
list[pos2] = temp;
}

public static void main(String[] args) {
int[] x = {1, 2, 3, 4, 5};
perm(x);
}
}

5.对于一个有N个整数元素的一维数组,找出它的子数组(数组中下标连续的元素组成的数组)之和的最大值。
下面给出几个例子(最大子数组用粗体表示):
数组:{ 1, -2, 3,5, -3, 2 },结果是:8
2) 数组:{ 0, -2, 3, 5, -1, 2 },结果是:9
3) 数组:{ -9, -2,-3, -5, -3 },结果是:-2
可以使用动态规划的思想求解:
public class MaxSum {
private static int max(int x, int y) {
return x > y? x: y;
}
public static int maxSum(int[] array) {
int n = array.length;
int[] start = new int[n];
int[] all = new int[n];
all[n - 1] = start[n - 1] = array[n - 1];
for(int i = n - 2; i >= 0;i--) {
start[i] = max(array[i], array[i] + start[i + 1]);
all[i] = max(start[i], all[i + 1]);
}
return all[0];
}
public static void main(String[] args) {
int[] x1 = { 1, -2, 3, 5,-3, 2 };
int[] x2 = { 0, -2, 3, 5,-1, 2 };
int[] x3 = { -9, -2, -3,-5, -3 };
System.out.println(maxSum(x1)); // 8
System.out.println(maxSum(x2)); // 9
System.out.println(maxSum(x3)); //-2
}
}

6.用递归实现字符串倒转
public class StringReverse {
public static String reverse(String originStr) {
if(originStr == null || originStr.length()== 1) {
return originStr;
}
return reverse(originStr.substring(1))+ originStr.charAt(0);
}
public static void main(String[] args) {
System.out.println(reverse("hello"));
}
}

7.输入一个正整数,将其分解为素数的乘积。
public class DecomposeInteger {
private static List list = new ArrayList();
public static void main(String[] args) {
System.out.print("请输入一个数: ");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
decomposeNumber(n);
System.out.print(n + " = ");
for(int i = 0; i < list.size() - 1; i++) {
System.out.print(list.get(i) + " * ");
}
System.out.println(list.get(list.size() - 1));
}
public static void decomposeNumber(int n) {
if(isPrime(n)) {
list.add(n);
list.add(1);
}
else {
doIt(n, (int)Math.sqrt(n));
}
}
public static void doIt(int n, int div) {
if(isPrime(div) && n % div == 0) {
list.add(div);
decomposeNumber(n / div);
}
else {
doIt(n, div - 1);
}
}
public static boolean isPrime(int n) {
for(int i = 2; i <= Math.sqrt(n);i++) {
if(n % i == 0) {
return false;
}
}
return true;
}
}

8、一个有n级的台阶,一次可以走1级、2级或3级,问走完n级台阶有多少种走法。
public class GoSteps {
public static int countWays(int n) {
if(n < 0) {
return 0;
}
else if(n == 0) {
return 1;
}
else {
return countWays(n - 1) + countWays(n - 2) + countWays(n -3);
}
}
public static void main(String[] args) {
System.out.println(countWays(5)); // 13
}
}

9.写一个算法判断一个英文单词的所有字母是否全都不同(不区分大小写)
public class AllNotTheSame {
public static boolean judge(String str) {
String temp = str.toLowerCase();
int[] letterCounter = new int[26];
for(int i = 0; i <temp.length(); i++) {
int index = temp.charAt(i)- 'a';
letterCounter[index]++;
if(letterCounter[index] > 1) {
return false;
}
}
return true;
}
public static void main(String[] args) {
System.out.println(judge("hello"));
System.out.print(judge("smile"));
}
}

10.有一个已经排好序的整数数组,其中存在重复元素,请将重复元素删除掉,例如,A= [1, 1, 2, 2, 3],处理之后的数组应当为A= [1, 2, 3]。
public class RemoveDuplication {
public static int[] removeDuplicates(int a[]) {
if(a.length <= 1) {
return a;
}
int index = 0;
for(int i = 1; i < a.length; i++) {
if(a[index] != a[i]) {
a[++index] = a[i];
}
}
int[] b = new int[index + 1];
System.arraycopy(a, 0, b, 0, b.length);
return b;
}
public static void main(String[] args) {
int[] a = {1, 1, 2, 2, 3};
a = removeDuplicates(a);
System.out.println(Arrays.toString(a));
}
}

11.给一个数组,其中有一个重复元素占半数以上,找出这个元素。
public class FindMost {
public static T find(T[] x){
T temp = null;
for(int i = 0, nTimes = 0; i< x.length;i++) {
if(nTimes == 0) {
temp= x[i];
nTimes= 1;
}
else {
if(x[i].equals(temp)) {
nTimes++;
}
else {
nTimes--;
}
}
}
return temp;
}
public static void main(String[] args) {
String[]strs = {"hello","kiss","hello","hello","maybe"};
System.out.println(find(strs));
}
}

12.编写一个方法求一个字符串的字节长度?
public int getWordCount(String s){
int length = 0;
for(int i = 0; i < s.length(); i++)
{
int ascii = Character.codePointAt(s, i);
if(ascii >= 0 && ascii <=255)
length++;
else
length += 2;

}
return length;
}

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Stella981 Stella981
2年前
Android So动态加载 优雅实现与原理分析
背景:漫品Android客户端集成适配转换功能(基于目标识别(So库35M)和人脸识别库(5M)),导致apk体积50M左右,为优化客户端体验,决定实现So文件动态加载.!(https://oscimg.oschina.net/oscnet/00d1ff90e4b34869664fef59e3ec3fdd20b.png)点击上方“蓝字”关注我
Stella981 Stella981
2年前
HIVE 时间操作函数
日期函数UNIX时间戳转日期函数: from\_unixtime语法:   from\_unixtime(bigint unixtime\, string format\)返回值: string说明: 转化UNIX时间戳(从19700101 00:00:00 UTC到指定时间的秒数)到当前时区的时间格式举例:hive   selec
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
2年前
Docker 部署SpringBoot项目不香吗?
  公众号改版后文章乱序推荐,希望你可以点击上方“Java进阶架构师”,点击右上角,将我们设为★“星标”!这样才不会错过每日进阶架构文章呀。  !(http://dingyue.ws.126.net/2020/0920/b00fbfc7j00qgy5xy002kd200qo00hsg00it00cj.jpg)  2
Wesley13 Wesley13
2年前
35岁是技术人的天花板吗?
35岁是技术人的天花板吗?我非常不认同“35岁现象”,人类没有那么脆弱,人类的智力不会说是35岁之后就停止发展,更不是说35岁之后就没有机会了。马云35岁还在教书,任正非35岁还在工厂上班。为什么技术人员到35岁就应该退役了呢?所以35岁根本就不是一个问题,我今年已经37岁了,我发现我才刚刚找到自己的节奏,刚刚上路。
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
4个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这