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,以及使用脚本开机自启(亲测)
前言 因为不想每次启动虚拟机都要手动启动一遍这些东西,所以想要设置成开机自启的状态 设置Tomcat开机自启 创建service文件 vi /etc/systemd/system/tomcat.service添加如下内容,注意修改启动脚本和关闭脚本的地址 [Unit] DescriptionTomcat9068 A…...
视觉SLAM:一直在入门,如何能精通,CV领域的绝境长城,
目录 前言 福利:文末有chat-gpt纯分享,无魔法,无限制 1 什么是SLAM? 2 为什么用SLAM? 3 视觉SLAM怎么实现? 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...
二叉搜索树的(查找、插入、删除)
一、二叉搜索树的概念 二叉搜索树又称二叉排序树,它或者是一棵空树,或者是具有以下性质的二叉树: 1、若它的左子树不为空,则左子树上所有节点的值都小于根节点的值; 2、若它的右子树不为空,则右子树上所有节点的值都…...
电力虚拟仿真 | 高压电气试验VR教学系统
在科技进步的推动下,我们的教育方式也在发生着翻天覆地的变化。其中,虚拟现实(VR)技术的出现,为我们提供了一种全新的、富有沉浸感的学习和培训方式。特别是在电力行业领域,例如,电力系统的维护…...
innovus如何设置size only
我正在「拾陆楼」和朋友们讨论有趣的话题,你⼀起来吧? 拾陆楼知识星球入口 给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 概念 方法重写 :子类中出现与父类一模一样的方法时(返回值类型,方法名和参数列表都相同),会出现覆盖效果,也称为重写或者复写。声明不变,重新实现。 3.7.2 使用场景与案例…...
国内常见的几款可视化Web组态软件
组态软件是一种用于控制和监控各种设备的软件,也是指在自动控制系统监控层一级的软件平台和开发环境。这类软件实际上也是一种通过灵活的组态方式,为用户提供快速构建工业自动控制系统监控功能的、通用层次的软件工具。通常用于工业控制,自动…...
通过 git上传到 gitee 仓库
介绍 Git是目前世界上最先进的分布式版本控制系统,有这么几个特点: 分布式 :是用来保存工程源代码历史状态的命令行工具。保存点 :保存点可以追溯源码中的文件,并能得到某个时间点上的整个工程项目额状态;…...
设置Windows主机的浏览器为wls2的默认浏览器
1. 准备工作 wsl是可以使用Windows主机上安装的exe程序,出于安全考虑,默认情况下改功能是无法使用。要使用的话,终端需要以管理员权限启动。 我这里以Windows Terminal为例,介绍如何默认使用管理员权限打开终端,具体…...
森林生物量(蓄积量)估算全流程
python森林生物量(蓄积量)估算全流程 一.哨兵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:数据定义语言,负责数据库定义、数据库对象定义,由CREATE、ALTER与DROP三个语法所组成DML:数据操作语言ÿ…...
2023年国赛数学建模思路 - 案例:退火算法
文章目录 1 退火算法原理1.1 物理背景1.2 背后的数学模型 2 退火算法实现2.1 算法流程2.2算法实现 建模资料 ## 0 赛题思路 (赛题出来以后第一时间在CSDN分享) 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 模型进阶训练技巧 自定义损失函数动态调整学习率 典型案例:loss上下震荡 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-BndMyRX0-1692613806232)(attachment:image-2.png)] 1、自定义损失函数 1、PyTorch已经提供了很多常用…...
【ArcGIS Pro二次开发】(61):样式(Style)和符号(Symbol)
在 ArcGIS Pro SDK 中,地图要素符号(Symbol)和符号样式(Style)是2个很重要的概念。 【Symbol】是用于表示地图上不同类型的要素(如点、线、面)的图形化表示。 在地图中,各种要素都…...
深入理解 HTTP/2:提升 Web 性能的秘密
HTTP/2 是一项重大的网络协议升级,旨在提升 Web 页面加载速度和性能。在这篇博客中,我们将深入探讨 HTTP/2 的核心概念以及如何使用它来加速网站。 什么是 HTTP/2? HTTP/2 是 HTTP 协议的下一个版本,旨在解决 HTTP/1.1 中的性能…...
逻辑回归:给不确定性划界的分类大师
想象你是一名医生。面对患者的检查报告(肿瘤大小、血液指标),你需要做出一个**决定性判断**:恶性还是良性?这种“非黑即白”的抉择,正是**逻辑回归(Logistic Regression)** 的战场&a…...
FFmpeg 低延迟同屏方案
引言 在实时互动需求激增的当下,无论是在线教育中的师生同屏演示、远程办公的屏幕共享协作,还是游戏直播的画面实时传输,低延迟同屏已成为保障用户体验的核心指标。FFmpeg 作为一款功能强大的多媒体框架,凭借其灵活的编解码、数据…...
蓝桥杯 2024 15届国赛 A组 儿童节快乐
P10576 [蓝桥杯 2024 国 A] 儿童节快乐 题目描述 五彩斑斓的气球在蓝天下悠然飘荡,轻快的音乐在耳边持续回荡,小朋友们手牵着手一同畅快欢笑。在这样一片安乐祥和的氛围下,六一来了。 今天是六一儿童节,小蓝老师为了让大家在节…...
Linux简单的操作
ls ls 查看当前目录 ll 查看详细内容 ls -a 查看所有的内容 ls --help 查看方法文档 pwd pwd 查看当前路径 cd cd 转路径 cd .. 转上一级路径 cd 名 转换路径 …...
STM32F4基本定时器使用和原理详解
STM32F4基本定时器使用和原理详解 前言如何确定定时器挂载在哪条时钟线上配置及使用方法参数配置PrescalerCounter ModeCounter Periodauto-reload preloadTrigger Event Selection 中断配置生成的代码及使用方法初始化代码基本定时器触发DCA或者ADC的代码讲解中断代码定时启动…...
Keil 中设置 STM32 Flash 和 RAM 地址详解
文章目录 Keil 中设置 STM32 Flash 和 RAM 地址详解一、Flash 和 RAM 配置界面(Target 选项卡)1. IROM1(用于配置 Flash)2. IRAM1(用于配置 RAM)二、链接器设置界面(Linker 选项卡)1. 勾选“Use Memory Layout from Target Dialog”2. 查看链接器参数(如果没有勾选上面…...
GitHub 趋势日报 (2025年06月08日)
📊 由 TrendForge 系统生成 | 🌐 https://trendforge.devlive.org/ 🌐 本日报中的项目描述已自动翻译为中文 📈 今日获星趋势图 今日获星趋势图 884 cognee 566 dify 414 HumanSystemOptimization 414 omni-tools 321 note-gen …...
Unsafe Fileupload篇补充-木马的详细教程与木马分享(中国蚁剑方式)
在之前的皮卡丘靶场第九期Unsafe Fileupload篇中我们学习了木马的原理并且学了一个简单的木马文件 本期内容是为了更好的为大家解释木马(服务器方面的)的原理,连接,以及各种木马及连接工具的分享 文件木马:https://w…...
基于TurtleBot3在Gazebo地图实现机器人远程控制
1. TurtleBot3环境配置 # 下载TurtleBot3核心包 mkdir -p ~/catkin_ws/src cd ~/catkin_ws/src git clone -b noetic-devel https://github.com/ROBOTIS-GIT/turtlebot3.git git clone -b noetic https://github.com/ROBOTIS-GIT/turtlebot3_msgs.git git clone -b noetic-dev…...
【分享】推荐一些办公小工具
1、PDF 在线转换 https://smallpdf.com/cn/pdf-tools 推荐理由:大部分的转换软件需要收费,要么功能不齐全,而开会员又用不了几次浪费钱,借用别人的又不安全。 这个网站它不需要登录或下载安装。而且提供的免费功能就能满足日常…...
