当前位置: 首页 > news >正文

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…),回文素数就是既是回文数又是素数(只能被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<Integer> list = new ArrayList<Integer>();

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> 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;

}
 

相关文章:

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) { i…...

点云平面拟合和球面拟合

一、介绍 In this tutorial we learn how to use a RandomSampleConsensus with a plane model to obtain the cloud fitting to this model. 二、代码 #include <iostream> #include <thread> #include <pcl/point_types.h> #include <pcl/common/io.…...

部署问题集合(十九)linux设置Tomcat、Docker,以及使用脚本开机自启(亲测)

前言 因为不想每次启动虚拟机都要手动启动一遍这些东西&#xff0c;所以想要设置成开机自启的状态 设置Tomcat开机自启 创建service文件 vi /etc/systemd/system/tomcat.service添加如下内容&#xff0c;注意修改启动脚本和关闭脚本的地址 [Unit] DescriptionTomcat9068 A…...

视觉SLAM:一直在入门,如何能精通,CV领域的绝境长城,

目录 前言 福利&#xff1a;文末有chat-gpt纯分享&#xff0c;无魔法&#xff0c;无限制 1 什么是SLAM&#xff1f; 2 为什么用SLAM&#xff1f; 3 视觉SLAM怎么实现&#xff1f; 4 前端视觉里程计 5 后端优化 6 回环检测 7 地图构建 8 结语 前言 上周的组会上&…...

【报错】yarn --version Unrecognized option: --version Error...

文章目录 问题分析解决问题 在使用 npm install -g yarn 全局安装 yarn 后,查看yarn 的版本号,报错如下 PS D:\global-data-display> yarn --version Unrecognized option: --version Error: Could...

二叉搜索树的(查找、插入、删除)

一、二叉搜索树的概念 二叉搜索树又称二叉排序树&#xff0c;它或者是一棵空树&#xff0c;或者是具有以下性质的二叉树: 1、若它的左子树不为空&#xff0c;则左子树上所有节点的值都小于根节点的值&#xff1b; 2、若它的右子树不为空&#xff0c;则右子树上所有节点的值都…...

电力虚拟仿真 | 高压电气试验VR教学系统

在科技进步的推动下&#xff0c;我们的教育方式也在发生着翻天覆地的变化。其中&#xff0c;虚拟现实&#xff08;VR&#xff09;技术的出现&#xff0c;为我们提供了一种全新的、富有沉浸感的学习和培训方式。特别是在电力行业领域&#xff0c;例如&#xff0c;电力系统的维护…...

innovus如何设置size only

我正在「拾陆楼」和朋友们讨论有趣的话题&#xff0c;你⼀起来吧&#xff1f; 拾陆楼知识星球入口 给instance设置size only属性命令如下: dbset [dbGet top.inst.name aa/bb -p] .dontTouch sizeOk 给一个module设置size only需要foreach循环一下: foreach inst [dbGet top.…...

Java之继承详解二

3.7 方法重写 3.7.1 概念 方法重写 &#xff1a;子类中出现与父类一模一样的方法时&#xff08;返回值类型&#xff0c;方法名和参数列表都相同&#xff09;&#xff0c;会出现覆盖效果&#xff0c;也称为重写或者复写。声明不变&#xff0c;重新实现。 3.7.2 使用场景与案例…...

国内常见的几款可视化Web组态软件

组态软件是一种用于控制和监控各种设备的软件&#xff0c;也是指在自动控制系统监控层一级的软件平台和开发环境。这类软件实际上也是一种通过灵活的组态方式&#xff0c;为用户提供快速构建工业自动控制系统监控功能的、通用层次的软件工具。通常用于工业控制&#xff0c;自动…...

通过 git上传到 gitee 仓库

介绍 Git是目前世界上最先进的分布式版本控制系统&#xff0c;有这么几个特点&#xff1a; 分布式 &#xff1a;是用来保存工程源代码历史状态的命令行工具。保存点 &#xff1a;保存点可以追溯源码中的文件&#xff0c;并能得到某个时间点上的整个工程项目额状态&#xff1b;…...

设置Windows主机的浏览器为wls2的默认浏览器

1. 准备工作 wsl是可以使用Windows主机上安装的exe程序&#xff0c;出于安全考虑&#xff0c;默认情况下改功能是无法使用。要使用的话&#xff0c;终端需要以管理员权限启动。 我这里以Windows Terminal为例&#xff0c;介绍如何默认使用管理员权限打开终端&#xff0c;具体…...

森林生物量(蓄积量)估算全流程

python森林生物量&#xff08;蓄积量&#xff09;估算全流程 一.哨兵2号获取/去云处理/提取参数1.1 影像处理与下载1.2 导入2A级产品1.3导入我们在第1步生成的云掩膜文件1.4.SNAP掩膜操作1.5采用gdal计算各类植被指数1.6 纹理特征参数提取 二.哨兵1号获取/处理/提取数据2.1 纹理…...

MySQL数据库概述

MySQL数据库概述 1 SQL SQL语句大小写不敏感。 SQL语句末尾应该使用分号结束。 1.1 SQL语句及相关操作示例 DDL&#xff1a;数据定义语言&#xff0c;负责数据库定义、数据库对象定义&#xff0c;由CREATE、ALTER与DROP三个语法所组成DML&#xff1a;数据操作语言&#xff…...

2023年国赛数学建模思路 - 案例:退火算法

文章目录 1 退火算法原理1.1 物理背景1.2 背后的数学模型 2 退火算法实现2.1 算法流程2.2算法实现 建模资料 ## 0 赛题思路 &#xff08;赛题出来以后第一时间在CSDN分享&#xff09; https://blog.csdn.net/dc_sinor?typeblog 1 退火算法原理 1.1 物理背景 在热力学上&a…...

怎么借助ChatGPT处理数据结构的问题

目录 使用ChatGPT进行数据格式化转换 代码示例 ChatGPT格式化数据提示语 代码示例 批量格式化数据提示语 代码示例 ChatGPT生成的格式化批处理代码 使用ChatGPT合并不同数据源的数据 合并数据提示语 自动合并数据提示语 ChatGPT生成的自动合并代码 结论 数据合并是…...

Docker容器无法启动 Cannot find /usr/local/tomcat/bin/setclasspath.sh

报错信息如下 解决办法 权限不够 加上--privileged 获取最大权限 docker run --privileged --name lenglianerqi -p 9266:8080 -v /opt/docker/lenglianerqi/webapps:/usr/local/tomcat/webapps/ -v /opt/docker/lenglianerqi/webapps/userfile:/usr/local/tomcat/webapps/u…...

Pytorch-day08-模型进阶训练技巧-checkpoint

PyTorch 模型进阶训练技巧 自定义损失函数动态调整学习率 典型案例&#xff1a;loss上下震荡 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-BndMyRX0-1692613806232)(attachment:image-2.png)] 1、自定义损失函数 1、PyTorch已经提供了很多常用…...

【ArcGIS Pro二次开发】(61):样式(Style)和符号(Symbol)

在 ArcGIS Pro SDK 中&#xff0c;地图要素符号&#xff08;Symbol&#xff09;和符号样式&#xff08;Style&#xff09;是2个很重要的概念。 【Symbol】是用于表示地图上不同类型的要素&#xff08;如点、线、面&#xff09;的图形化表示。 在地图中&#xff0c;各种要素都…...

深入理解 HTTP/2:提升 Web 性能的秘密

HTTP/2 是一项重大的网络协议升级&#xff0c;旨在提升 Web 页面加载速度和性能。在这篇博客中&#xff0c;我们将深入探讨 HTTP/2 的核心概念以及如何使用它来加速网站。 什么是 HTTP/2&#xff1f; HTTP/2 是 HTTP 协议的下一个版本&#xff0c;旨在解决 HTTP/1.1 中的性能…...

网络编程(Modbus进阶)

思维导图 Modbus RTU&#xff08;先学一点理论&#xff09; 概念 Modbus RTU 是工业自动化领域 最广泛应用的串行通信协议&#xff0c;由 Modicon 公司&#xff08;现施耐德电气&#xff09;于 1979 年推出。它以 高效率、强健性、易实现的特点成为工业控制系统的通信标准。 包…...

测试markdown--肇兴

day1&#xff1a; 1、去程&#xff1a;7:04 --11:32高铁 高铁右转上售票大厅2楼&#xff0c;穿过候车厅下一楼&#xff0c;上大巴车 &#xffe5;10/人 **2、到达&#xff1a;**12点多到达寨子&#xff0c;买门票&#xff0c;美团/抖音&#xff1a;&#xffe5;78人 3、中饭&a…...

MMaDA: Multimodal Large Diffusion Language Models

CODE &#xff1a; https://github.com/Gen-Verse/MMaDA Abstract 我们介绍了一种新型的多模态扩散基础模型MMaDA&#xff0c;它被设计用于在文本推理、多模态理解和文本到图像生成等不同领域实现卓越的性能。该方法的特点是三个关键创新:(i) MMaDA采用统一的扩散架构&#xf…...

论文解读:交大港大上海AI Lab开源论文 | 宇树机器人多姿态起立控制强化学习框架(一)

宇树机器人多姿态起立控制强化学习框架论文解析 论文解读&#xff1a;交大&港大&上海AI Lab开源论文 | 宇树机器人多姿态起立控制强化学习框架&#xff08;一&#xff09; 论文解读&#xff1a;交大&港大&上海AI Lab开源论文 | 宇树机器人多姿态起立控制强化…...

GitHub 趋势日报 (2025年06月08日)

&#x1f4ca; 由 TrendForge 系统生成 | &#x1f310; https://trendforge.devlive.org/ &#x1f310; 本日报中的项目描述已自动翻译为中文 &#x1f4c8; 今日获星趋势图 今日获星趋势图 884 cognee 566 dify 414 HumanSystemOptimization 414 omni-tools 321 note-gen …...

Linux C语言网络编程详细入门教程:如何一步步实现TCP服务端与客户端通信

文章目录 Linux C语言网络编程详细入门教程&#xff1a;如何一步步实现TCP服务端与客户端通信前言一、网络通信基础概念二、服务端与客户端的完整流程图解三、每一步的详细讲解和代码示例1. 创建Socket&#xff08;服务端和客户端都要&#xff09;2. 绑定本地地址和端口&#x…...

群晖NAS如何在虚拟机创建飞牛NAS

套件中心下载安装Virtual Machine Manager 创建虚拟机 配置虚拟机 飞牛官网下载 https://iso.liveupdate.fnnas.com/x86_64/trim/fnos-0.9.2-863.iso 群晖NAS如何在虚拟机创建飞牛NAS - 个人信息分享...

vue3 daterange正则踩坑

<el-form-item label"空置时间" prop"vacantTime"> <el-date-picker v-model"form.vacantTime" type"daterange" start-placeholder"开始日期" end-placeholder"结束日期" clearable :editable"fal…...

算法打卡第18天

从中序与后序遍历序列构造二叉树 (力扣106题) 给定两个整数数组 inorder 和 postorder &#xff0c;其中 inorder 是二叉树的中序遍历&#xff0c; postorder 是同一棵树的后序遍历&#xff0c;请你构造并返回这颗 二叉树 。 示例 1: 输入&#xff1a;inorder [9,3,15,20,7…...

Vue3中的computer和watch

computed的写法 在页面中 <div>{{ calcNumber }}</div>script中 写法1 常用 import { computed, ref } from vue; let price ref(100);const priceAdd () > { //函数方法 price 1price.value ; }//计算属性 let calcNumber computed(() > {return ${p…...